Files
memoryweave/go/internal/api/middleware/auth.go
T
xiaowei 6667d42e14 feat(M1): Go API 服务器骨架 + Auth 中间件 + /health 端点
M1.3: Go HTTP 服务器 (net/http, /health, Auth middleware)
M1.4: Protobuf IPC 定义 (Go↔Rust Consolidation 服务)

验收:
- /health → 200 {"status":"ok","service":"zhiyid","version":"0.1.0"}
- 无 X-API-Key → 401
- 正确 Key → 200
- 错误 Key → 401

文件:
- go/cmd/zhiyid/main.go (127 行, 优雅关闭)
- go/internal/api/server.go (31 行, 路由注册)
- go/internal/api/middleware/auth.go (38 行, X-API-Key)
- go/internal/api/routes/health.go (24 行)
- go/proto/consolidate.proto (72 行, 4 RPC)
2026-05-28 17:16:52 +08:00

42 lines
822 B
Go

// API Key 认证中间件
package middleware
import (
"encoding/json"
"net/http"
"os"
)
// 豁免认证的路径
var exemptPaths = map[string]bool{
"/health": true,
}
// Auth 返回一个 HTTP 中间件,验证 X-API-Key 请求头
func Auth(next http.Handler) http.Handler {
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
apiKey = "zhiyi-dev-key-2026"
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 豁免路径跳过认证
if exemptPaths[r.URL.Path] {
next.ServeHTTP(w, r)
return
}
key := r.Header.Get("X-API-Key")
if key != apiKey {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "unauthorized",
})
return
}
next.ServeHTTP(w, r)
})
}