2026-04-25 13:21:39 +08:00

35 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package http
import (
"net/http"
"hyapp/services/gateway-service/internal/auth"
)
// apiHandler 包装所有 gateway 业务 HTTP API 的公共入口能力。
// 顺序必须是 request_id -> auth -> handler保证鉴权失败也能返回可追踪 request_id。
func apiHandler(jwtVerifier *auth.Verifier, next http.HandlerFunc) http.Handler {
return withRequestID(withAuth(jwtVerifier, next))
}
// publicAPIHandler 包装不需要 access token 的业务 API。
// 登录注册链路仍然有 request_id但不能要求用户已经有 access token。
func publicAPIHandler(next http.HandlerFunc) http.Handler {
return withRequestID(next)
}
// withAuth 在 transport 层完成鉴权失败响应写入。
// auth 包只返回身份校验结果,避免底层鉴权模块绑定 gateway 的 JSON envelope。
func withAuth(jwtVerifier *auth.Verifier, next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
userID, err := jwtVerifier.VerifyUserID(request.Header.Get("Authorization"))
if err != nil {
writeError(writer, request, http.StatusUnauthorized, codeUnauthorized, "unauthorized")
return
}
ctx := auth.WithUserID(request.Context(), userID)
next.ServeHTTP(writer, request.WithContext(ctx))
})
}