zquit.go 1.1 KB
Newer Older
Vladimir Barsukov's avatar
Vladimir Barsukov committed
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package zquit

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"sync/atomic"
	"syscall"
)

type ZQuit struct {
	isQuit bool
	delta  atomic.Int32
	wg     sync.WaitGroup
}

func Default() *ZQuit {
	return &ZQuit{}
}

func (q *ZQuit) Add(delta int) {
	q.delta.Add(int32(delta))
	q.wg.Add(delta)
}

func (q *ZQuit) Inc() {
	q.Add(1)
}

func (q *ZQuit) Done() {
	q.delta.Add(-1)
	q.wg.Done()
}

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

func (q *ZQuit) IncDefer() func() {
	q.Inc()

	return func() {
		q.Done()
	}
}

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

func (q *ZQuit) Delta() int32 {
	return q.delta.Load()
}

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()
}