forked from mtusi2026/mtusi2026lab2
92 lines
2.2 KiB
Go
92 lines
2.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"runtime/debug"
|
|
"time"
|
|
"uuid"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
|
|
"messenger/internal/domain"
|
|
)
|
|
|
|
const (
|
|
headerRequestID = "X-Request-Id"
|
|
headerUserID = "X-User-Id"
|
|
)
|
|
|
|
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{}
|
|
|
|
func (h *Handler) Authenticate(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
id, ok := parseUUID(r.Header.Get(headerUserID))
|
|
if !ok {
|
|
h.fail(w, r, domain.ErrUnauthorized)
|
|
return
|
|
}
|
|
user, err := h.users.Authenticate(r.Context(), id)
|
|
if err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, user)))
|
|
})
|
|
}
|
|
|
|
func actor(r *http.Request) domain.User {
|
|
u, ok := r.Context().Value(ctxKey{}).(domain.User)
|
|
if !ok {
|
|
panic(errors.New("handler: actor requested on unauthenticated route"))
|
|
}
|
|
return u
|
|
}
|