-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
76 lines (63 loc) · 1.91 KB
/
handlers.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
package main
import (
"fmt"
"log"
"net/http"
"time"
)
const (
headerAppName = "X-App-Name"
headerAppVersion = "X-App-Version"
logFormat = "Remote Addr: %s Host Addr: %s Method: %s Path: %s Proto: %s Status: %d Length: %d User Agent: %s Duration: %v"
)
func httpEcho(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(responseStatusCodeFlag)
w.Write([]byte(responseBodyFlag))
}
func httpHealth(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("{status: ok}"))
}
func appendHeaders(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(headerAppName, Name)
w.Header().Add(headerAppVersion, Version)
next.ServeHTTP(w, r)
}
}
// Custom ResponseWriter to save information to log
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
length int
}
func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
return &loggingResponseWriter{
ResponseWriter: w,
}
}
func (lrw *loggingResponseWriter) Header() http.Header {
return lrw.ResponseWriter.Header()
}
func (lrw *loggingResponseWriter) Write(b []byte) (int, error) {
lrw.length = len(b)
return lrw.ResponseWriter.Write(b)
}
func (lrw *loggingResponseWriter) WriteHeader(statusCode int) {
lrw.statusCode = statusCode
lrw.ResponseWriter.WriteHeader(statusCode)
}
func logRequest(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
lrw := NewLoggingResponseWriter(w)
next.ServeHTTP(lrw, r)
defer func(start time.Time) {
reqDuration := time.Now().Sub(start)
httpRequestLog := fmt.Sprintf(logFormat, r.RemoteAddr, r.Host, r.Method, r.URL.Path, r.Proto, lrw.statusCode, lrw.length, r.UserAgent(), reqDuration)
if logFullHeader {
httpRequestLog = fmt.Sprintf("%s Full header: %v", httpRequestLog, r.Header)
}
log.Println(httpRequestLog)
}(time.Now())
}
}