43 lines
1.0 KiB
Go
43 lines
1.0 KiB
Go
package httpserver
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/middleware"
|
|
"github.com/gorilla/sessions"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
func loggerMiddleware(l *zap.Logger, sessionStore sessions.Store) func(next http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
|
t1 := time.Now()
|
|
|
|
cu, ok := getCurrentUser(r, sessionStore)
|
|
var userID string
|
|
if ok {
|
|
userID = cu.ID.String()
|
|
}
|
|
|
|
defer func() {
|
|
l.Info("HTTP",
|
|
zap.String("proto", r.Proto),
|
|
zap.String("method", r.Method),
|
|
zap.String("path", r.URL.Path),
|
|
zap.Duration("dur", time.Since(t1)),
|
|
zap.Int("status", ww.Status()),
|
|
zap.Int("size", ww.BytesWritten()),
|
|
zap.String("ip", r.RemoteAddr),
|
|
zap.String("reqId", middleware.GetReqID(r.Context())),
|
|
zap.String("userID", userID),
|
|
zap.String("username", cu.TwitterUsername))
|
|
}()
|
|
|
|
next.ServeHTTP(ww, r)
|
|
}
|
|
return http.HandlerFunc(fn)
|
|
}
|
|
}
|