42 lines
803 B
Go
42 lines
803 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"log"
|
||
|
|
"net/http"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
// responseWriter is a custom wrapper to capture the status code
|
||
|
|
type responseWriter struct {
|
||
|
|
http.ResponseWriter
|
||
|
|
status int
|
||
|
|
}
|
||
|
|
|
||
|
|
func (rw *responseWriter) WriteHeader(code int) {
|
||
|
|
rw.status = code
|
||
|
|
rw.ResponseWriter.WriteHeader(code)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Logger is a middleware that logs each incoming HTTP request
|
||
|
|
func Logger() Middleware {
|
||
|
|
return func(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
start := time.Now()
|
||
|
|
|
||
|
|
// Default status is 200 OK
|
||
|
|
rw := &responseWriter{ResponseWriter: w, status: http.StatusOK}
|
||
|
|
|
||
|
|
next.ServeHTTP(rw, r)
|
||
|
|
|
||
|
|
log.Printf(
|
||
|
|
"[%s] %s %s | %d | %v",
|
||
|
|
r.Method,
|
||
|
|
r.Host,
|
||
|
|
r.URL.Path,
|
||
|
|
rw.status,
|
||
|
|
time.Since(start),
|
||
|
|
)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|