-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_log.go
52 lines (44 loc) · 1.21 KB
/
handler_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
package httpu
import (
"bufio"
"log"
"net"
"net/http"
"strings"
"github.com/gohxs/httpu/chain"
)
/////////////////////////
// Log handler
/////
// LogHelper struct to handle write logs
type LogHelper struct {
http.ResponseWriter
statusCode int
}
// WriteHeader hijack write header to track httpStatus
func (l *LogHelper) WriteHeader(code int) {
l.statusCode = code
l.ResponseWriter.WriteHeader(code)
}
// Hijack hihack wrapper for hijacker users (websocket?)
func (l *LogHelper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker := l.ResponseWriter.(http.Hijacker)
return hijacker.Hijack()
}
// LogHandler returns an handler that logs output using default logger
func LogHandler(log *log.Logger, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := &LogHelper{w, 200}
if next != nil {
next.ServeHTTP(l, r)
}
raddr := strings.Split(r.RemoteAddr, ":")[0]
log.Printf("(%s) %s %s - [%d %s]", raddr, r.Method, r.URL.Path, l.statusCode, http.StatusText(l.statusCode))
}
}
//ChainLogger middleware for chainer
func ChainLogger(log *log.Logger) chain.Func {
return func(next http.HandlerFunc) http.HandlerFunc {
return LogHandler(log, next.ServeHTTP)
}
}