-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
58 lines (51 loc) · 1.04 KB
/
log.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
package api
import (
"bufio"
"net"
"net/http"
"time"
)
type loggingWriter struct {
http.ResponseWriter
header bool
Status int
Length int
}
func (w *loggingWriter) Write(b []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(b)
w.Length += n
return
}
func (w *loggingWriter) WriteHeader(code int) {
if w.header {
return
}
w.Status = code
w.ResponseWriter.WriteHeader(code)
w.header = true
return
}
func (w *loggingWriter) Flush() {
h, ok := w.ResponseWriter.(http.Flusher)
if !ok {
return
}
h.Flush()
}
func (w *loggingWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
h, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, http.ErrHijacked
}
return h.Hijack()
}
func (a *Application) LoggingMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l := &loggingWriter{ResponseWriter: w}
t := time.Now()
h.ServeHTTP(l, r)
if a.Logging != nil {
a.Logging.Println(r.Method, r.URL, r.Proto, l.Status, l.Length, time.Now().Sub(t))
}
})
}