feat: add API Key input and authentication for TTS requests
This commit is contained in:
@@ -30,6 +30,7 @@ type ServerConfig struct {
|
||||
|
||||
// TTSConfig 包含Microsoft TTS API配置
|
||||
type TTSConfig struct {
|
||||
ApiKey string `mapstructure:"api_key"`
|
||||
Region string `mapstructure:"region"`
|
||||
DefaultVoice string `mapstructure:"default_voice"`
|
||||
DefaultRate string `mapstructure:"default_rate"`
|
||||
|
||||
@@ -38,3 +38,21 @@ func OpenAIAuth(apiToken string, next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// TTSAuth 是用于验证 TTS API 接口的中间件
|
||||
func TTSAuth(apiKey string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// 从查询参数中获取 api_key
|
||||
queryKey := r.URL.Query().Get("api_key")
|
||||
|
||||
// 如果 apiKey 配置为空字符串,表示不需要验证
|
||||
if apiKey != "" && queryKey != apiKey {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte("未授权访问: 无效的 API 密钥"))
|
||||
return
|
||||
}
|
||||
|
||||
// 验证通过,继续处理请求
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -30,8 +30,10 @@ func SetupRoutes(cfg *config.Config, ttsService tts.Service) (http.Handler, erro
|
||||
// 设置API文档路由
|
||||
mux.HandleFunc("/api-doc", pagesHandler.HandleAPIDoc)
|
||||
|
||||
// 设置TTS API路由
|
||||
mux.HandleFunc("/tts", ttsHandler.HandleTTS)
|
||||
// 设置TTS API路由 - 添加认证中间件
|
||||
ttsHandlerFunc := http.HandlerFunc(ttsHandler.HandleTTS)
|
||||
authenticatedTTSHandler := middleware.TTSAuth(cfg.TTS.ApiKey, ttsHandlerFunc)
|
||||
mux.Handle("/tts", authenticatedTTSHandler)
|
||||
|
||||
// 设置语音列表API路由
|
||||
mux.HandleFunc("/voices", voicesHandler.HandleVoices)
|
||||
|
||||
Reference in New Issue
Block a user