forked from andig/gravo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
91 lines (74 loc) · 2.01 KB
/
handler.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
89
90
91
package main
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"time"
)
// cors adds required headers to responses such that direct access works.
func cors(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Headers", "accept, content-type")
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Origin", "*")
f(w, r)
}
}
func allowed(f http.HandlerFunc, methods ...string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
for _, allowed := range methods {
if r.Method == allowed {
f(w, r)
return
}
}
http.Error(w, "Bad method; supported OPTIONS, POST", http.StatusBadRequest)
}
}
// logger logs inbound request and body without consuming the request
func logger(f http.HandlerFunc, debug bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
var body []byte
if debug {
// get request body
var err error
body, err = ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
// get response body
w = newLoggingResponseWriter(w)
}
f(w, r)
duration := time.Since(start)
log.Printf("%v %v (%dms)", r.Method, r.URL.Path, duration.Milliseconds())
if debug {
log.Println("Request:\n" + string(body))
log.Println("Response:\n" + string(w.(loggingResponseWriter).body))
}
}
}
type loggingResponseWriter struct {
http.ResponseWriter
body []byte
}
func newLoggingResponseWriter(w http.ResponseWriter) loggingResponseWriter {
return loggingResponseWriter{w, []byte{}}
}
func (w loggingResponseWriter) Write(b []byte) (int, error) {
w.body = append(w.body, b...)
return w.ResponseWriter.Write(b)
}
// handler builds inbound request processing stack
func handler(f http.HandlerFunc, debug bool) http.HandlerFunc {
return cors(
allowed(
logger(
f,
debug),
http.MethodGet, http.MethodOptions, http.MethodPost),
)
}