-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.go
81 lines (65 loc) · 1.52 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
"net/http"
"time"
)
func (s *server) fixIPAddress(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var ipAddress string
var ipSources = []string{
r.Header.Get("True-Client-IP"),
r.Header.Get("True-Real-IP"),
r.Header.Get("X-Forwarded-For"),
r.Header.Get("X-Originating-IP"),
}
for _, ip := range ipSources {
if ip != "" {
ipAddress = ip
break
}
}
if ipAddress != "" {
r.RemoteAddr = ipAddress
}
h(w, r)
}
}
type (
responseData struct {
status int
size int
}
loggingResponseWriter struct {
http.ResponseWriter
responseData *responseData
}
)
func (r loggingResponseWriter) Write(b []byte) (int, error) {
size, err := r.ResponseWriter.Write(b)
r.responseData.size += size
return size, err
}
func (r loggingResponseWriter) WriteHeader(statusCode int) {
r.ResponseWriter.WriteHeader(statusCode)
r.responseData.status = statusCode
}
func (s *server) withLogging(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
responseData := &responseData{
status: 0,
size: 0,
}
lrw := loggingResponseWriter{
ResponseWriter: w,
responseData: responseData,
}
h.ServeHTTP(lrw, r) // serve the original request
uri := r.RequestURI
method := r.Method
duration := time.Since(start)
// log request details
fmt.Printf("%s %s (%d) - %d bytes, %v\n", method, uri, lrw.responseData.status, lrw.responseData.size, duration)
}
}