forked from hyperledger-archives/burrow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
77 lines (61 loc) · 1.74 KB
/
server.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
package service
import (
"context"
"net/http"
"github.com/hyperledger/burrow/vent/config"
"github.com/hyperledger/burrow/vent/logger"
)
// Server exposes HTTP endpoints for the service
type Server struct {
Config *config.VentConfig
Log *logger.Logger
Consumer *Consumer
mux *http.ServeMux
stopCh chan bool
}
// NewServer returns a new HTTP server
func NewServer(cfg *config.VentConfig, log *logger.Logger, consumer *Consumer) *Server {
// setup handlers
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler(log, consumer))
return &Server{
Config: cfg,
Log: log,
Consumer: consumer,
mux: mux,
stopCh: make(chan bool, 1),
}
}
// Run starts the HTTP server
func (s *Server) Run() {
s.Log.Info("msg", "Starting HTTP Server")
// start http server
httpServer := &http.Server{Addr: s.Config.HTTPAddr, Handler: s}
go func() {
s.Log.Info("msg", "HTTP Server listening", "address", s.Config.HTTPAddr)
httpServer.ListenAndServe()
}()
// wait for stop signal
<-s.stopCh
s.Log.Info("msg", "Shutting down HTTP Server...")
httpServer.Shutdown(context.Background())
}
// ServeHTTP dispatches the HTTP requests using the Server Mux
func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
s.mux.ServeHTTP(resp, req)
}
// Shutdown gracefully shuts down the HTTP Server
func (s *Server) Shutdown() {
s.stopCh <- true
}
func healthHandler(log *logger.Logger, consumer *Consumer) func(resp http.ResponseWriter, req *http.Request) {
return func(resp http.ResponseWriter, req *http.Request) {
err := consumer.Health()
if err != nil {
resp.WriteHeader(http.StatusServiceUnavailable)
} else {
resp.WriteHeader(http.StatusOK)
}
log.Info("msg", "GET /health", "err", err)
}
}