forked from ozonmp/omp-demo-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
status.go
61 lines (49 loc) · 1.6 KB
/
status.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
package server
import (
"encoding/json"
"fmt"
"net/http"
"sync/atomic"
"github.com/hablof/logistic-package-api/internal/config"
"github.com/rs/zerolog/log"
)
func createStatusServer(cfg *config.Config, isReady *atomic.Value) *http.Server {
statusAddr := fmt.Sprintf("%s:%v", cfg.Status.Host, cfg.Status.Port)
mux := http.DefaultServeMux
mux.HandleFunc(cfg.Status.LivenessPath, livenessHandler)
mux.HandleFunc(cfg.Status.ReadinessPath, readinessHandler(isReady))
mux.HandleFunc(cfg.Status.VersionPath, versionHandler(cfg))
statusServer := &http.Server{
Addr: statusAddr,
Handler: mux,
}
return statusServer
}
func livenessHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
func readinessHandler(isReady *atomic.Value) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
if isReady == nil || !isReady.Load().(bool) {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}
}
func versionHandler(cfg *config.Config) func(w http.ResponseWriter, _ *http.Request) {
return func(w http.ResponseWriter, _ *http.Request) {
data := map[string]interface{}{
"name": cfg.Project.Name,
"debug": cfg.Project.Debug,
"environment": cfg.Project.Environment,
"version": cfg.Project.Version,
"commitHash": cfg.Project.CommitHash,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Error().Err(err).Msg("Service information encoding error")
}
}
}