44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
package middleware
|
|
|
|
import "net/http"
|
|
import "time"
|
|
|
|
import "codit/internal/models"
|
|
import "codit/internal/util"
|
|
|
|
type statusRecorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (r *statusRecorder) WriteHeader(code int) {
|
|
r.status = code
|
|
r.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func AccessLog(logger *util.Logger, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var recorder *statusRecorder
|
|
var start time.Time
|
|
var duration time.Duration
|
|
var userLabel string
|
|
var user models.User
|
|
var ok bool
|
|
if logger == nil {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
recorder = &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
|
start = time.Now()
|
|
next.ServeHTTP(recorder, r)
|
|
duration = time.Since(start)
|
|
userLabel = "-"
|
|
user, ok = UserFromContext(r.Context())
|
|
if ok && user.Username != "" {
|
|
userLabel = user.Username
|
|
}
|
|
logger.Write("api", util.LOG_INFO, "method=%s path=%s remote=%s user=%s status=%d dur_ms=%d",
|
|
r.Method, r.URL.Path, r.RemoteAddr, userLabel, recorder.status, duration.Milliseconds())
|
|
})
|
|
}
|