zquit.go 1.07 KB
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
}

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

func (q *ZQuit) Wait() {
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
32
33
	q.Shutdown()

Vladimir Barsukov's avatar
Vladimir Barsukov committed
34
35
36
37
	q.wg.Wait()
}

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

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

Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
45
46
func (q *ZQuit) Val() int {
	return q.wg.Val()
Vladimir Barsukov's avatar
Vladimir Barsukov committed
47
48
49
}

func (q *ZQuit) WaitInterruptPrePost(pre func(), post func()) {
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
50
51
52
	if pre != nil {
		pre()
	}
Vladimir Barsukov's avatar
Vladimir Barsukov committed
53
54
55
56
57
58
59
60

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

	<-c

	q.Wait()

Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
61
62
63
	if post != nil {
		post()
	}
Vladimir Barsukov's avatar
Vladimir Barsukov committed
64
65
66
}

func (q *ZQuit) WaitInterrupt() {
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
67
	q.WaitInterruptPrePost(nil, nil)
Vladimir Barsukov's avatar
Vladimir Barsukov committed
68
69
}

Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
70
func (q *ZQuit) Middleware(c *gin.Context) {
Vladimir Barsukov's avatar
Vladimir Barsukov committed
71
72
73
74
75
76
77
78
79
80
	if q.isQuit {
		c.Data(http.StatusServiceUnavailable, "text/plain", []byte("server shutdown"))
		return
	}

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

	c.Next()
}
Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
81
82
83
84

func (q *ZQuit) Shutdown() {
	q.isQuit = true
}