42 lines
964 B
Go
42 lines
964 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"floorvisualizer/internal/logger"
|
||
|
|
)
|
||
|
|
|
||
|
|
type responseWriter struct {
|
||
|
|
http.ResponseWriter
|
||
|
|
statusCode int
|
||
|
|
wroteHeader bool
|
||
|
|
}
|
||
|
|
|
||
|
|
func (rw *responseWriter) WriteHeader(code int) {
|
||
|
|
if !rw.wroteHeader {
|
||
|
|
rw.statusCode = code
|
||
|
|
rw.wroteHeader = true
|
||
|
|
}
|
||
|
|
rw.ResponseWriter.WriteHeader(code)
|
||
|
|
}
|
||
|
|
|
||
|
|
func (rw *responseWriter) Write(b []byte) (int, error) {
|
||
|
|
if !rw.wroteHeader {
|
||
|
|
rw.statusCode = http.StatusOK
|
||
|
|
rw.wroteHeader = true
|
||
|
|
}
|
||
|
|
return rw.ResponseWriter.Write(b)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Logging wraps an http.Handler with access logging, like Fiber's requestLogMiddleware.
|
||
|
|
// Format: METHOD /path 200 1.234ms
|
||
|
|
func Logging(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
start := time.Now()
|
||
|
|
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
|
||
|
|
next.ServeHTTP(rw, r)
|
||
|
|
logger.Info("%s %s %d %s", r.Method, r.URL.Path, rw.statusCode, time.Since(start))
|
||
|
|
})
|
||
|
|
}
|