57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
/*
|
|
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
*/
|
|
|
|
package http
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type loggerResponseWriter struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
responseSize int
|
|
}
|
|
|
|
func (w *loggerResponseWriter) WriteHeader(statusCode int) {
|
|
w.statusCode = statusCode
|
|
w.ResponseWriter.WriteHeader(statusCode)
|
|
}
|
|
|
|
func (w *loggerResponseWriter) Write(b []byte) (int, error) {
|
|
w.responseSize += len(b)
|
|
return w.ResponseWriter.Write(b)
|
|
}
|
|
|
|
func (w *loggerResponseWriter) Flush() {
|
|
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
|
f.Flush()
|
|
}
|
|
}
|
|
|
|
func LogRequest(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
t := time.Now()
|
|
logger := loggerResponseWriter{w, 0, 0}
|
|
|
|
next.ServeHTTP(&logger, r)
|
|
|
|
statusCode := logger.statusCode
|
|
if statusCode == 0 {
|
|
statusCode = http.StatusOK
|
|
}
|
|
log.Printf("HTTP - %s %s \"%s\" %d %d %s\n",
|
|
RemoteAddr(r),
|
|
r.Method,
|
|
r.URL.Path,
|
|
statusCode,
|
|
logger.responseSize,
|
|
time.Since(t),
|
|
)
|
|
})
|
|
}
|