go/webutil/middleware-logging.go

48 lines
867 B
Go
Raw Permalink Normal View History

2024-11-11 05:36:55 +00:00
package webutil
import (
"log"
"net/http"
"os"
"time"
)
var _log = log.New(os.Stderr, "", 0)
type responseWriterWrapper struct {
http.ResponseWriter
httpStatus int
responseSize int
}
func (w *responseWriterWrapper) WriteHeader(status int) {
w.httpStatus = status
w.ResponseWriter.WriteHeader(status)
}
func (w *responseWriterWrapper) Write(b []byte) (int, error) {
if w.httpStatus == 0 {
w.httpStatus = 200
}
w.responseSize += len(b)
return w.ResponseWriter.Write(b)
}
func WithLogging(inner http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
t := time.Now()
wrapper := responseWriterWrapper{w, 0, 0}
inner(&wrapper, r)
_log.Printf("%s \"%s %s %s\" %d %d %v\n",
r.RemoteAddr,
r.Method,
r.URL.Path,
r.Proto,
wrapper.httpStatus,
wrapper.responseSize,
time.Since(t),
)
}
}