This repository has been archived on 2022-05-25. You can view files and clone it, but cannot push or open issues or pull requests.
elon-eats-my-tweets/httpserver/middleware.go

43 lines
1.0 KiB
Go
Raw Normal View History

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