zquit.go 1007 Bytes
Newer Older
Vladimir Barsukov's avatar
Vladimir Barsukov committed
1
2
3
package zquit

import (
Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
4
	"git.barsukov.pro/barsukov/zgo/zwg"
Vladimir Barsukov's avatar
Vladimir Barsukov committed
5
6
7
8
9
10
11
12
13
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

type ZQuit struct {
	isQuit bool
Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
14
	wg     *zwg.Zwg
Vladimir Barsukov's avatar
Vladimir Barsukov committed
15
16
}

Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
17
18
19
20
func New() *ZQuit {
	return &ZQuit{
		wg: zwg.New(),
	}
Vladimir Barsukov's avatar
Vladimir Barsukov committed
21
22
23
}

func (q *ZQuit) Inc() {
Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
24
	q.wg.Inc()
Vladimir Barsukov's avatar
Vladimir Barsukov committed
25
26
27
28
29
30
31
32
33
34
35
}

func (q *ZQuit) Done() {
	q.wg.Done()
}

func (q *ZQuit) Wait() {
	q.wg.Wait()
}

func (q *ZQuit) IncDefer() func() {
Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
36
	return q.wg.IncDefer()
Vladimir Barsukov's avatar
Vladimir Barsukov committed
37
38
39
40
41
42
}

func (q *ZQuit) IsQuit() bool {
	return q.isQuit
}

Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
43
44
func (q *ZQuit) Val() int {
	return q.wg.Val()
Vladimir Barsukov's avatar
Vladimir Barsukov committed
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
71
72
73
74
}

func (q *ZQuit) WaitInterruptPrePost(pre func(), post func()) {
	pre()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)

	<-c

	q.Wait()

	post()
}

func (q *ZQuit) WaitInterrupt() {
	q.WaitInterruptPrePost(func() {}, func() {})
}

func (q *ZQuit) ZQuitMiddleware(c *gin.Context) {
	if q.isQuit {
		c.Data(http.StatusServiceUnavailable, "text/plain", []byte("server shutdown"))
		return
	}

	cancel := q.IncDefer()
	defer cancel()

	c.Next()
}