-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
90 lines (78 loc) · 2.06 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
package main
// HTTP admin API
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
func handleError(w http.ResponseWriter, err error, code int) {
Logger.Log(NewLogMessage(
ERROR,
LogContext{
"error": fmt.Sprintf("%s", err),
},
func() string {
return fmt.Sprintf("[%v]", w)
},
))
w.WriteHeader(code)
}
func shutdownHttpHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("{\"message\": \"shutting down server\"}"))
Shutdown()
}
func versionHttpHandler(w http.ResponseWriter, r *http.Request) {
v := GetVersion()
str, err := json.Marshal(v)
if err != nil {
handleError(w, err, 500)
}
if _, err := w.Write([]byte(str)); err != nil {
handleError(w, err, 500)
}
}
func configHttpHandler(w http.ResponseWriter, r *http.Request) {
conf := GetConfiguration()
str, err := json.Marshal(conf)
if err != nil {
handleError(w, err, 500)
return
}
_, err = w.Write([]byte(str))
if err != nil {
handleError(w, err, 500)
}
}
func addPratchettHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Clacks-Overhead", "GNU Terry Pratchett")
next.ServeHTTP(w, r)
})
}
func setContentTypeHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
}
//nolint
var HttpServer *http.Server
func InitApi() {
conf := GetConfiguration()
router := mux.NewRouter().StrictSlash(true)
InitPrometheus(router)
router.Use(addPratchettHeader)
router.Use(setContentTypeHeader)
router.HandleFunc("/v1/config", configHttpHandler)
router.HandleFunc("/v1/shutdown", shutdownHttpHandler)
router.HandleFunc("/v1/version", versionHttpHandler)
log.Printf("starting HTTP server on ':%d'\n", conf.HttpPort)
HttpServer := &http.Server{Handler: router, Addr: fmt.Sprintf(":%d", conf.HttpPort)}
// don't block the main thread with this jazz
go func() {
log.Printf(fmt.Sprintf("%s", HttpServer.ListenAndServe()))
}()
}