-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
102 lines (88 loc) · 2.1 KB
/
http.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package service
import (
"context"
"net/http"
"sync"
"time"
"github.com/JokeTrue/image-previewer/pkg/logging"
)
var (
ready bool
readyLock sync.RWMutex
alive bool
aliveLock sync.RWMutex
)
func SetReady(state bool) {
readyLock.Lock()
defer readyLock.Unlock()
ready = state
}
func IsReady() bool {
readyLock.RLock()
defer readyLock.RUnlock()
return ready
}
func SetAlive(state bool) {
aliveLock.Lock()
defer aliveLock.Unlock()
alive = state
}
func IsAlive() bool {
aliveLock.RLock()
defer aliveLock.RUnlock()
return alive
}
func init() {
SetAlive(true)
}
type HTTPServer struct {
Server *http.Server
shutdownTimeout time.Duration
done chan struct{}
}
func NewHTTPServer(addr string, shutdownTimeout time.Duration, router http.Handler) *HTTPServer {
r := http.NewServeMux()
r.Handle("/", router)
r.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if IsAlive() {
w.WriteHeader(http.StatusNoContent)
return
}
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
})
r.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
if IsReady() {
w.WriteHeader(http.StatusNoContent)
return
}
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
})
srv := &http.Server{
Addr: addr,
Handler: r,
}
return &HTTPServer{
shutdownTimeout: shutdownTimeout,
Server: srv,
done: make(chan struct{}),
}
}
func (s *HTTPServer) Start() {
go func() {
defer close(s.done)
logging.Infof("starting http server on %s", s.Server.Addr)
if err := s.Server.ListenAndServe(); err != http.ErrServerClosed {
logging.WithError(err).Fatal("http server failure")
}
logging.Infof("http server on %s stopped listening", s.Server.Addr)
}()
}
func (s *HTTPServer) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)
if err := s.Server.Shutdown(ctx); err != nil {
logging.WithError(err).Error("http shutdown error")
}
logging.Infof("http server on %s stopped", s.Server.Addr)
<-s.done
cancel()
}