38 lines
815 B
Go
38 lines
815 B
Go
package middleware
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// responseWriter 是用于捕获状态码的响应写入器
|
|
type responseWriter struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
func (rw *responseWriter) WriteHeader(code int) {
|
|
rw.statusCode = code
|
|
rw.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
// Logging 中间件记录请求日志
|
|
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)
|
|
|
|
duration := time.Since(start)
|
|
slog.Info("http_request",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", rw.statusCode,
|
|
"duration_ms", float64(duration.Microseconds())/1000,
|
|
"remote_addr", r.RemoteAddr,
|
|
)
|
|
})
|
|
}
|