forked from mtusi2026/mtusi2026lab2
Перенесена ЛР1
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const UserContextKey contextKey = "current_user"
|
||||
|
||||
// RequireAuth проверяет наличие и валидность X-User-Id
|
||||
func RequireAuth(st *store.MemoryStore, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := GetRequestID(r.Context())
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
|
||||
if userID == "" {
|
||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "missing X-User-Id header", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
//существует ли чел
|
||||
user, err := st.GetUserByID(userID)
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "user not found", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), UserContextKey, user)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// чисто чтоб зареганного получить из контекста
|
||||
func GetCurrentUser(ctx context.Context) domain.User {
|
||||
if val, ok := ctx.Value(UserContextKey).(domain.User); ok {
|
||||
return val
|
||||
}
|
||||
return domain.User{}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// responseWriterInterceptor перехватывает статус-код ответа для логов
|
||||
type responseWriterInterceptor struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *responseWriterInterceptor) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
interceptor := &responseWriterInterceptor{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался
|
||||
}
|
||||
|
||||
next.ServeHTTP(interceptor, r)
|
||||
|
||||
reqID := GetRequestID(r.Context())
|
||||
duration := time.Since(start)
|
||||
|
||||
// метаданные без r.Body
|
||||
log.Printf(
|
||||
"[HTTP] %s %s | status: %d | duration: %v | request_id: %s",
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
interceptor.statusCode,
|
||||
duration,
|
||||
reqID,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
reqID := GetRequestID(r.Context())
|
||||
//из контракта: не раскрывать stack trace и внутренности
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal server error",
|
||||
reqID,
|
||||
)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RequestIDKey contextKey = "request_id"
|
||||
|
||||
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.Header.Get("X-Request-Id")
|
||||
if reqID == "" {
|
||||
reqID = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// GetRequestID достает ID запроса из контекста
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
if val, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return val
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
Reference in New Issue
Block a user