This repository has been archived by the owner on May 13, 2022. It is now read-only.
/
server.go
81 lines (66 loc) · 1.85 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
78
79
80
81
package service
import (
"context"
"encoding/json"
"net/http"
"github.com/hyperledger/burrow/logging"
"github.com/hyperledger/burrow/vent/config"
)
// Server exposes HTTP endpoints for the service
type Server struct {
Config *config.VentConfig
Log *logging.Logger
Consumer *Consumer
mux *http.ServeMux
stopCh chan bool
}
// NewServer returns a new HTTP server
func NewServer(cfg *config.VentConfig, log *logging.Logger, consumer *Consumer) *Server {
// setup handlers
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler(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.InfoMsg("Starting HTTP Server")
// start http server
httpServer := &http.Server{Addr: s.Config.HTTPListenAddress, Handler: s}
go func() {
s.Log.InfoMsg("HTTP Server listening", "address", s.Config.HTTPListenAddress)
httpServer.ListenAndServe()
}()
// wait for stop signal
<-s.stopCh
s.Log.InfoMsg("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(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)
bs, err := json.Marshal(consumer.StatusMessage(req.Context()))
if err == nil {
resp.Header().Set("Content-Type", "application/json")
resp.Write(bs)
}
}
}
}