go_import_excel_pg/internal/middleware.go

27 lines
604 B
Go
Raw Normal View History

2024-02-22 10:43:39 +07:00
package internal
import (
"context"
"net/http"
"strings"
)
type contextKey string
const UserContext contextKey = "user"
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Authorization header is required", http.StatusUnauthorized)
return
}
authToken := strings.Split(authHeader, "Bearer ")[1]
ctx := context.WithValue(r.Context(), UserContext, ParseJWT(authToken))
req := r.WithContext(ctx)
next.ServeHTTP(w, req)
})
}