forked from mtusi2026/mtusi2026lab2
Начало реализации сервиса.
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func NewRouter() chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Use(requestIdMiddleware, loggingMiddleware)
|
||||
return r
|
||||
}
|
||||
|
||||
func requestIdMiddleware(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestID := uuid.New()
|
||||
w.Header().Set(HeaderRequestID, requestID.String())
|
||||
ctx = context.WithValue(ctx, HeaderRequestID, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
status := wrapped.Status()
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
slog.InfoContext(r.Context(), "http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"duration", time.Since(started),
|
||||
"bytes", wrapped.BytesWritten(),
|
||||
"request_id", w.Header().Get(HeaderRequestID),
|
||||
)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user