-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.go
64 lines (54 loc) · 1.49 KB
/
middleware.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
package registry
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
)
// logger wraps a Handler with some quick logging (after request)
func logger(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"[Registry] %s\t%s\t%s",
r.Method,
r.RequestURI,
time.Since(start),
)
})
}
func contentTypeJSON(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
inner.ServeHTTP(w, r)
})
}
// Instead of squashing a potential error in serializing, do it on startup to
// ensure we can write directly. This relies on DontPanicError still in lieu of
// creating a const string like
// {"message":"Internal Server Error. Don't Panic. We will."}
var rawPanicMessage []byte
func init() {
var err error
rawPanicMessage, err = json.Marshal(DontPanicError)
if err != nil {
log.Panicf("Unable to initialize our panic message: %v", err)
os.Exit(3)
}
}
func recoverHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %+v", err)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusInternalServerError)
w.Write(rawPanicMessage)
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}