-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (69 loc) · 1.87 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"time"
"github.com/elnormous/contenttype"
)
func main() {
ctx := context.Background()
healthcheck := flag.Bool("healthcheck", false, "Do health check")
flag.Parse()
if *healthcheck {
doHealthcheck(ctx)
}
server := &http.Server{
Addr: getAddr(),
ReadHeaderTimeout: 3 * time.Second,
}
http.HandleFunc("/", handler)
err := server.ListenAndServe()
if err != nil {
fmt.Print(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
supportedContentTypes := []contenttype.MediaType{
contenttype.NewMediaType("text/plain"),
contenttype.NewMediaType("application/json"),
contenttype.NewMediaType("text/html"),
}
contentType, _, err := contenttype.GetAcceptableMediaType(r, supportedContentTypes)
if err != nil {
contentType = contenttype.NewMediaType("text/plain")
}
// Explicitly set the Content-Type header on non-HEAD requests
// if the request "application/json". This is because
// http.DetectContentType() is not able to detect it.
if "application/json" == contentType.String() && r.Method != http.MethodHead {
w.Header().Set("Content-Type", contentType.String())
}
status, stateFormat := getStatusAndFormat(State(r.Context()))
w.WriteHeader(status)
// If this is a HEAD request we will not write a response body
if r.Method == http.MethodHead {
return
}
writeBody(w, contentType.String(), stateFormat)
}
func getAddr() string {
addr, present := os.LookupEnv("SYSTEMD_STATE_ADDR")
if !present {
addr = ":80"
}
return addr
}
// We do a health check simply by checking if we can get a systemd
// status or not. Notice the health check is not to check whether
// systemd is healthy or not but to check if this monitoring software
// itself is healthy.
func doHealthcheck(ctx context.Context) {
_, err := State(ctx)
if err != nil {
os.Exit(1)
}
os.Exit(0)
}