-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
84 lines (70 loc) · 1.72 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
package main
import (
_ "embed"
"flag"
"fmt"
"html/template"
"log"
"net/http"
)
//go:embed index.html
var content string
var templates = template.Must(template.New("index.html").Parse(content))
type State struct {
Visits int
Healthy bool
}
func index(s *State) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := templates.Execute(w, s); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
s.Visits += 1
}
}
func health(s *State) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if s.Healthy {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusServiceUnavailable)
}
case http.MethodPost:
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
params := r.URL.Query()
h, ok := params["h"]
if !ok {
w.WriteHeader(http.StatusNotModified)
return
}
if len(h) != 1 || (h[0] != "true" && h[0] != "false") {
w.WriteHeader(http.StatusBadRequest)
return
}
healthy := h[0] == "true"
if healthy == s.Healthy {
w.WriteHeader(http.StatusNotModified)
return
}
s.Healthy = healthy
http.Redirect(w, r, "/", http.StatusSeeOther)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
func main() {
addr := flag.String("addr", "127.0.0.1", "address to listen on")
port := flag.Int("port", 8000, "TCP port to listen on")
flag.Parse()
s := State{Healthy: true}
http.HandleFunc("/", index(&s))
http.HandleFunc("/health", health(&s))
log.Printf("Listening on %s:%d...", *addr, *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", *addr, *port), nil))
}