feat: 使用 viper 绑定配置,open ai api 添加认证配置
This commit is contained in:
40
internal/http/middleware/auth.go
Normal file
40
internal/http/middleware/auth.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// OpenAIAuth 中间件验证 OpenAI API 请求的令牌
|
||||
func OpenAIAuth(apiToken string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// 如果没有配置令牌,跳过验证
|
||||
if apiToken == "" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取请求头中的 Authorization
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
http.Error(w, "未提供授权令牌", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证格式是否为 "Bearer {token}"
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
http.Error(w, "授权格式无效", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证令牌是否正确
|
||||
if parts[1] != apiToken {
|
||||
http.Error(w, "令牌无效", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 令牌验证通过,继续处理请求
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -36,8 +36,13 @@ func SetupRoutes(cfg *config.Config, ttsService tts.Service) (http.Handler, erro
|
||||
// 设置语音列表API路由
|
||||
mux.HandleFunc("/voices", voicesHandler.HandleVoices)
|
||||
|
||||
mux.HandleFunc("/v1/audio/speech", ttsHandler.HandleOpenAITTS)
|
||||
mux.HandleFunc("/audio/speech", ttsHandler.HandleOpenAITTS)
|
||||
// 创建OpenAI兼容接口的处理器,添加验证中间件
|
||||
openAIHandler := http.HandlerFunc(ttsHandler.HandleOpenAITTS)
|
||||
authenticatedHandler := middleware.OpenAIAuth(cfg.OpenAI.ApiKey, openAIHandler)
|
||||
|
||||
// 应用OpenAI兼容的路由
|
||||
mux.Handle("/v1/audio/speech", authenticatedHandler)
|
||||
mux.Handle("/audio/speech", authenticatedHandler)
|
||||
|
||||
// 设置静态文件服务
|
||||
fs := http.FileServer(http.Dir("./web/static"))
|
||||
|
||||
Reference in New Issue
Block a user