package handler import ( "context" "errors" "net/http" "runtime/debug" "strings" "time" "uuid" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "messenger/internal/domain" ) const ( headerRequestID = "X-Request-Id" headerWWWAuthenticate = "WWW-Authenticate" bearerChallenge = `Bearer realm="messenger"` basicChallenge = `Basic realm="messenger", charset="UTF-8"` ) func RequestID(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set(headerRequestID, uuid.New().String()) next.ServeHTTP(w, r) }) } func (h *Handler) AccessLog(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) next.ServeHTTP(ww, r) route := r.URL.Path if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" { route = rc.RoutePattern() } h.log.Info("request", "request_id", w.Header().Get(headerRequestID), "method", r.Method, "route", route, "status", ww.Status(), "duration_ms", time.Since(start).Milliseconds(), ) }) } func (h *Handler) Recoverer(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { rec := recover() if rec == nil { return } if rec == http.ErrAbortHandler { panic(rec) } h.log.Error("panic", "request_id", w.Header().Get(headerRequestID), "method", r.Method, "path", r.URL.Path, "panic", rec, "stack", string(debug.Stack())) writeError(w, http.StatusInternalServerError, "internal_error", "internal server error") }() next.ServeHTTP(w, r) }) } type ctxKey struct{} type principal struct { user domain.User token string } func (h *Handler) Authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token, ok := authCredentials(r, "Bearer") if !ok || token == "" { h.fail(w, r, domain.ErrUnauthorized) return } user, err := h.auth.Authenticate(r.Context(), token) if err != nil { h.fail(w, r, err) return } ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token}) next.ServeHTTP(w, r.WithContext(ctx)) }) } func authCredentials(r *http.Request, scheme string) (string, bool) { gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ") if !ok || !strings.EqualFold(gotScheme, scheme) { return "", false } return credentials, true } func current(r *http.Request) principal { p, ok := r.Context().Value(ctxKey{}).(principal) if !ok { panic(errors.New("handler: actor requested on unauthenticated route")) } return p } func actor(r *http.Request) domain.User { return current(r).user }