forked from practicalgo/code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
86 lines (69 loc) · 2.11 KB
/
Copy pathserver.go
File metadata and controls
86 lines (69 loc) · 2.11 KB
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
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
)
type appConfig struct {
logger *log.Logger
}
type app struct {
config appConfig
handler func(w http.ResponseWriter, r *http.Request, config appConfig)
}
func (a app) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.handler(w, r, a.config)
}
func apiHandler(w http.ResponseWriter, r *http.Request, config appConfig) {
fmt.Fprintf(w, "Hello, world!")
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request, config appConfig) {
if r.Method != "GET" {
config.logger.Printf("error=\"Invalid request\" path=%s method=%s", r.URL.Path, r.Method)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
fmt.Fprintf(w, "ok")
}
func panicHandler(w http.ResponseWriter, r *http.Request, config appConfig) {
panic("I panicked")
}
func setupHandlers(mux *http.ServeMux, config appConfig) {
mux.Handle("/healthz", &app{config: config, handler: healthCheckHandler})
mux.Handle("/api", &app{config: config, handler: apiHandler})
mux.Handle("/panic", &app{config: config, handler: panicHandler})
}
func loggingMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
h.ServeHTTP(w, r)
log.Printf("protocol=%s path=%s method=%s duration=%f", r.Proto, r.URL.Path, r.Method, time.Now().Sub(startTime).Seconds())
})
}
func panicMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rValue := recover(); rValue != nil {
log.Println("panic detected when handling request", rValue)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Unexpected server error occured")
}
}()
h.ServeHTTP(w, r)
})
}
func main() {
listenAddr := os.Getenv("LISTEN_ADDR")
if len(listenAddr) == 0 {
listenAddr = ":8080"
}
config := appConfig{
logger: log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile),
}
mux := http.NewServeMux()
setupHandlers(mux, config)
m := loggingMiddleware(panicMiddleware(mux))
log.Fatal(http.ListenAndServe(listenAddr, m))
}