-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
58 lines (48 loc) · 1.33 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
package main
import (
"context"
"errors"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog/log"
)
// server is a simple http server that exposes health check endpoint
type server struct {
srv *http.Server
}
// newServer creates a new server listening on the given address
func newServer(webListenAddress string) *server {
mux := http.NewServeMux()
s := &server{
srv: &http.Server{
Addr: webListenAddress,
Handler: mux,
ReadTimeout: 2 * time.Second,
},
}
mux.HandleFunc("/healthz", s.healthz)
mux.Handle("/metrics", promhttp.Handler())
return s
}
// startAsync starts the server asynchronously
func (s *server) startAsync() {
go func() {
if err := s.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatal().Err(err).Msg("server failed")
}
}()
}
// stop gracefully shuts down the server
func (s *server) stop() {
// we don't expect any long running connections,
// so we can safely shutdown the server using background context
if err := s.srv.Shutdown(context.Background()); err != nil {
log.Fatal().Err(err).Msg("failed to shutdown server")
}
}
// healthz is a simple health check endpoint
func (s *server) healthz(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok")) // nolint: errcheck
}