-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.go
95 lines (73 loc) · 2.03 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
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"github.com/harvester/vm-dhcp-controller/pkg/config"
)
const defaultPort = 8080
type HTTPServer struct {
*config.HTTPServerOptions
srv *http.Server
router *mux.Router
}
func NewHTTPServer(httpServerOptions *config.HTTPServerOptions) *HTTPServer {
return &HTTPServer{
HTTPServerOptions: httpServerOptions,
router: mux.NewRouter(),
}
}
func (s *HTTPServer) registerProbeHandlers() {
s.router.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(map[string]bool{"ok": true}); err != nil {
logrus.Fatal(err)
}
})
s.router.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(map[string]bool{"ok": true}); err != nil {
logrus.Fatal(err)
}
})
}
func (s *HTTPServer) RegisterControllerHandlers() {
s.registerProbeHandlers()
if s.DebugMode {
s.router.Handle("/ipams/{networkName:.*}", listIPByNetworkHandler(s.IPAllocator))
s.router.Handle("/caches/{networkName:.*}", listCacheByNetworkHandler(s.CacheAllocator))
}
s.router.Handle("/metrics", metricsHandler(s.MetricsAllocator))
}
func (s *HTTPServer) RegisterAgentHandlers() {
s.registerProbeHandlers()
if s.DebugMode {
s.router.Handle("/leases", listLeaseHandler(s.DHCPAllocator))
}
}
func (s *HTTPServer) Run() error {
logrus.Info("Starting HTTP server")
s.srv = &http.Server{
Handler: s.router,
Addr: fmt.Sprintf(":%d", defaultPort),
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
logrus.Infof("Listening on port: %d", defaultPort)
return s.srv.ListenAndServe()
}
func (s *HTTPServer) stop(ctx context.Context) error {
logrus.Info("Stopping HTTP server")
return s.srv.Shutdown(ctx)
}
func Cleanup(ctx context.Context, srv *HTTPServer) <-chan error {
errCh := make(chan error)
go func() {
<-ctx.Done()
defer close(errCh)
errCh <- srv.stop(ctx)
}()
return errCh
}