-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
55 lines (49 loc) · 1.33 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
package httplog
import (
"net/http"
)
// WithLogging provides HTTP logging capabilities to an http.Handler.
// It is used as http.Handler middleware. Requires the http.Handler and a
// pre-configured Logger.
// Returns a new handler that wraps the supplied handler and provides logging
// functionality.
// Example:
//
// type customHandler {}
//
// func (h *customHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// w.WriteHeader(200)
// // ...your handler logic goes here...
// }
//
// func main() {
// // Configure a logger
// l := httplog.New(os.Stdout)
//
// // And use the middleware
// http.Handle("/logs", httplog.WithLogging(&customHandler{}, l))
// http.ListenAndServe(":8080", nil)
// }
//
func WithLogging(next http.Handler, l Logger) http.Handler {
return &loggingHandler{next: next, logger: l}
}
type loggingHandler struct {
logger Logger
next http.Handler
}
func (h loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.logger.SetRequestInfo(r)
lrw := &loggingResponseWriter{ResponseWriter: w}
h.next.ServeHTTP(lrw, r)
h.logger.SetStatus(lrw.Status)
defer h.logger.Log()
}
type loggingResponseWriter struct {
http.ResponseWriter
Status int
}
func (lrw *loggingResponseWriter) WriteHeader(status int) {
lrw.Status = status
lrw.ResponseWriter.WriteHeader(status)
}