package auth import ( "context" "net/http" ) // authMiddleware 验证 Authorization 头和项目 ID 头 func AuthMiddleware(next http.Handler, authToken, projectIDHeader string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 验证 Authorization 头 authHeader := r.Header.Get("Authorization") if authHeader == "" { http.Error(w, "Authorization header required", http.StatusUnauthorized) return } expected := "Bearer " + authToken if authHeader != expected { http.Error(w, "Invalid authorization token", http.StatusUnauthorized) return } // 提取项目 ID 头并存储到请求上下文中,供 extractRequestContext 使用 projectID := r.Header.Get(projectIDHeader) if projectID != "" { // 将项目 ID 存储到上下文中 ctx := context.WithValue(r.Context(), "projectID", projectID) r = r.WithContext(ctx) } next.ServeHTTP(w, r) }) }