46 lines
851 B
Go
46 lines
851 B
Go
package handlers
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type statusRecorder struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
func (sr *statusRecorder) WriteHeader(code int) {
|
|
sr.statusCode = code
|
|
sr.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func (sr *statusRecorder) Write(b []byte) (int, error) {
|
|
if sr.statusCode == 0 {
|
|
sr.statusCode = http.StatusOK
|
|
}
|
|
|
|
return sr.ResponseWriter.Write(b)
|
|
}
|
|
|
|
func LogMiddleware(h http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
rec := &statusRecorder{ResponseWriter: w}
|
|
|
|
h.ServeHTTP(rec, r)
|
|
duration := time.Since(start)
|
|
|
|
statusCode := rec.statusCode
|
|
|
|
log.Printf("%s %s %s from %s - %d %s in %s\n",
|
|
r.Method,
|
|
r.URL.Path,
|
|
r.Proto,
|
|
r.RemoteAddr,
|
|
statusCode,
|
|
http.StatusText(statusCode),
|
|
duration.String())
|
|
})
|
|
}
|