forked from mtusi2026/mtusi2026lab3
Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Middleware struct {
|
||||
authService *service.AuthService
|
||||
instanceID string
|
||||
}
|
||||
|
||||
func NewMiddleware(authService *service.AuthService, instanceID string) *Middleware {
|
||||
|
||||
return &Middleware{
|
||||
authService: authService,
|
||||
instanceID: instanceID,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (m *Middleware) Auth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := m.authService.ValidateSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := WithUserID(r.Context(), userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := uuid.NewString()
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := WithRequestID(r.Context(), requestID)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) InstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", m.instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user