-
Notifications
You must be signed in to change notification settings - Fork 5
/
hostname.go
68 lines (58 loc) · 1.6 KB
/
hostname.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
package main
import (
"io"
"log"
"net/http"
"os"
"time"
)
var isHealthy = true
// loggingHandler is a http middleware that logs each request
func loggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
log.Printf("[%s] %q from %s takes %v\n", r.Method, r.URL.String(), r.RemoteAddr, t2.Sub(t1))
}
return http.HandlerFunc(fn)
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
h, _ := os.Hostname()
// echo message if given, otherwise just echo hostname
msg := os.Getenv("MESSAGE")
if msg != "" {
msg += " from "
}
msg += h + "\n"
io.WriteString(w, msg)
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
h, _ := os.Hostname()
if !isHealthy {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Oops!" + " from " + h + "\n"))
} else {
io.WriteString(w, "ok"+" from "+h+"\n")
}
}
func healthToggleHandler(w http.ResponseWriter, r *http.Request) {
h, _ := os.Hostname()
if r.Method == "POST" {
isHealthy = !isHealthy
w.Write([]byte("done" + " from " + h + "\n"))
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("Sorry, only POST is allowed.\n"))
}
}
func main() {
http.Handle("/", loggingHandler(http.HandlerFunc(helloHandler)))
http.Handle("/health", loggingHandler(http.HandlerFunc(healthHandler)))
http.Handle("/toggle.hz", loggingHandler(http.HandlerFunc(healthToggleHandler)))
log.Printf("start serving...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatalf("start server error: %v\n", err)
}
}