/
graceful.go
70 lines (62 loc) · 1.75 KB
/
graceful.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"fmt"
"github.com/go-martini/martini"
"log"
"net/http"
"os"
"os/signal"
"sync"
"sync/atomic"
"time"
)
type GracefulShutdown struct { // {{{
timeout time.Duration
wg sync.WaitGroup
functions []func()
} // }}}
func NewGracefulShutdown(t time.Duration) *GracefulShutdown { // {{{
return &GracefulShutdown{timeout: t}
} // }}}
func (g *GracefulShutdown) Handler(c martini.Context) { // {{{
g.wg.Add(1)
c.Next()
g.wg.Done()
} // }}}
func (g *GracefulShutdown) RunOnShutDown(f func()) error { // {{{
g.functions = append(g.functions, f)
return nil
} // }}}
func (g *GracefulShutdown) WaitForSignal(signals ...os.Signal) error { // {{{
sigchan := make(chan os.Signal)
signal.Notify(sigchan, signals...)
<-sigchan
log.Println("Waiting for all requests to finish")
for _, f := range g.functions {
f()
}
waitChan := make(chan struct{})
go func() {
g.wg.Wait()
waitChan <- struct{}{}
}()
select {
case <-time.After(g.timeout):
return fmt.Errorf("timed out waiting %v for shutdown", g.timeout)
case <-waitChan:
return nil
}
} // }}}
type ConnectionLimit struct { // {{{
numConnections int32
limit int32
} // }}}
func (c *ConnectionLimit) Handler(ctx martini.Context, rw http.ResponseWriter) { // {{{
if atomic.AddInt32(&c.numConnections, 1) > c.limit {
http.Error(rw, "maximum connections exceeded", http.StatusServiceUnavailable)
atomic.AddInt32(&c.numConnections, -1)
return
}
ctx.Next()
atomic.AddInt32(&c.numConnections, -1)
} // }}}