-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
50 lines (43 loc) · 1.38 KB
/
handler.go
File metadata and controls
50 lines (43 loc) · 1.38 KB
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
// Package httplog implements logging of HTTP requests.
package httplog
import (
"log"
"net/http"
"sync"
)
// LogFn is a function responsible for logging an HTTP request/response.
type LogFn func(*Record)
// LoggingHandler wraps an http.Handler in order to log processed requests
// using the provided function. If the logging function needs to reference
// the passed in *Record, it must make a copy before returning.
type LoggingHandler struct {
http.Handler
LogFn
}
// NewLoggingHandler returns an http.Handler that logs completed requests
// using the given LogFn. If the second parameter is nil, it uses DefaultLogFn.
func NewLoggingHandler(handler http.Handler, fn LogFn) http.Handler {
if fn == nil {
return &LoggingHandler{Handler: handler, LogFn: DefaultLogFn}
}
return &LoggingHandler{Handler: handler, LogFn: fn}
}
func (l *LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
record := recordPool.Get().(*Record)
record.Start()
record.Request.Update(r)
rw := WrapResponseWriter(w)
l.Handler.ServeHTTP(rw, r)
record.Response.Update(rw)
record.End()
if l.LogFn != nil {
l.LogFn(record)
}
record.Reset()
recordPool.Put(record)
}
// DefaultLogFn logs the record to log.Println using BasicLogFormat.
func DefaultLogFn(record *Record) {
log.Println(record.Format(BasicLogFormat))
}
var recordPool = sync.Pool{New: func() interface{} { return new(Record) }}