build: 升级go版本到1.26并添加限流中间件
1. 调整go.mod将Go版本升级至1.26 2. 新增速率限制和并发限制中间件,将其加入路由中间件链 3. 重构TTS处理逻辑,将限流逻辑迁移至中间件统一处理 4. 优化CORS中间件代码,移除冗余日志和格式调整
This commit is contained in:
+1
-17
@@ -39,23 +39,7 @@ func OpenaiTTSHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
select {
|
r.Body = http.MaxBytesReader(w, r.Body, common.MaxRequestBodySize)
|
||||||
case middleware.ConcurrencySem <- struct{}{}:
|
|
||||||
defer func() { <-middleware.ConcurrencySem }()
|
|
||||||
default:
|
|
||||||
log.Printf("警告: 已达到最大并发请求数限制,拒绝请求 - 客户端IP: %s", middleware.GetClientIP(r))
|
|
||||||
middleware.SendJSONError(w, http.StatusServiceUnavailable, "Server is busy, maximum concurrent requests reached. Please try again later.", "concurrency_limit_error", "max_concurrent_requests")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
clientIP := middleware.GetClientIP(r)
|
|
||||||
if !middleware.GlobalRateLimiter.Allow(clientIP) {
|
|
||||||
log.Printf("警告: 已超过IP速率限制,拒绝请求 - 客户端IP: %s", clientIP)
|
|
||||||
middleware.SendJSONError(w, http.StatusTooManyRequests, "Rate limit exceeded. Please try again later.", "rate_limit_error", "rate_limit_exceeded")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, common.MaxRequestBodySize)
|
|
||||||
body, err := io.ReadAll(r.Body)
|
body, err := io.ReadAll(r.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if strings.Contains(err.Error(), "request body too large") {
|
if strings.Contains(err.Error(), "request body too large") {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
module github.com/volcano-tts/tts-api
|
module github.com/volcano-tts/tts-api
|
||||||
|
|
||||||
go 1.19
|
go 1.26
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
|
|||||||
+12
-17
@@ -1,4 +1,4 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
@@ -8,8 +8,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
allowedOrigins []string
|
allowedOrigins []string
|
||||||
allowAllOrigins bool
|
allowAllOrigins bool
|
||||||
corsMaxAgeHeader = "86400"
|
corsMaxAgeHeader = "86400"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -46,9 +46,6 @@ func InitCORSConfig() {
|
|||||||
}
|
}
|
||||||
if len(allowedOrigins) > 0 {
|
if len(allowedOrigins) > 0 {
|
||||||
log.Printf("已配置 %d 个允许的跨域来源白名单", len(allowedOrigins))
|
log.Printf("已配置 %d 个允许的跨域来源白名单", len(allowedOrigins))
|
||||||
for _, o := range allowedOrigins {
|
|
||||||
log.Printf(" - %s", o)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,9 +53,7 @@ func isValidOrigin(origin string) bool {
|
|||||||
if origin == "" || origin == "null" || origin == "nil" {
|
if origin == "" || origin == "null" || origin == "nil" {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
// 使用小写比较,避免大小写问题
|
if !strings.HasPrefix(origin, "http://") && !strings.HasPrefix(origin, "https://") {
|
||||||
lowerOrigin := strings.ToLower(origin)
|
|
||||||
if !strings.HasPrefix(lowerOrigin, "http://") && !strings.HasPrefix(lowerOrigin, "https://") {
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@@ -66,28 +61,24 @@ func isValidOrigin(origin string) bool {
|
|||||||
|
|
||||||
func matchOrigin(origin string) (string, bool) {
|
func matchOrigin(origin string) (string, bool) {
|
||||||
if !isValidOrigin(origin) {
|
if !isValidOrigin(origin) {
|
||||||
log.Printf("[CORS] Origin %q 验证失败", origin)
|
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
if allowAllOrigins {
|
if allowAllOrigins {
|
||||||
log.Printf("[CORS] Origin %q 匹配 allowAllOrigins", origin)
|
|
||||||
return "*", true
|
return "*", true
|
||||||
}
|
}
|
||||||
normalized := normalizeOrigin(origin)
|
normalized := normalizeOrigin(origin)
|
||||||
log.Printf("[CORS] 检查 origin %q (normalized: %q) 对比白名单: %v", origin, normalized, allowedOrigins)
|
|
||||||
for _, allowed := range allowedOrigins {
|
for _, allowed := range allowedOrigins {
|
||||||
if allowed == normalized {
|
if allowed == normalized {
|
||||||
log.Printf("[CORS] Origin %q 匹配白名单 %q", origin, allowed)
|
|
||||||
return origin, true
|
return origin, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("[CORS] Origin %q 未匹配任何白名单", origin)
|
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
func CORS(next http.Handler) http.Handler {
|
func CORS(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
origin := r.Header.Get("Origin")
|
origin := r.Header.Get("Origin")
|
||||||
|
isPreflight := r.Method == http.MethodOptions
|
||||||
|
|
||||||
if origin != "" {
|
if origin != "" {
|
||||||
allowOrigin, matched := matchOrigin(origin)
|
allowOrigin, matched := matchOrigin(origin)
|
||||||
@@ -107,16 +98,20 @@ func CORS(next http.Handler) http.Handler {
|
|||||||
w.Header().Set("Vary", vary+", Origin")
|
w.Header().Set("Vary", vary+", Origin")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Printf("CORS拦截: 来源=%q 路径=%s 方法=%s 客户端IP=%s",
|
log.Printf("CORS拦截: 来源=%q 路径=%s 方法=%s 客户端=%s",
|
||||||
origin, r.URL.Path, r.Method, GetClientIP(r))
|
origin, r.URL.Path, r.Method, GetClientIP(r))
|
||||||
|
if isPreflight {
|
||||||
|
w.WriteHeader(http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.Method == http.MethodOptions {
|
if isPreflight {
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RateLimit(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
clientIP := GetClientIP(r)
|
||||||
|
if !GlobalRateLimiter.Allow(clientIP) {
|
||||||
|
log.Printf("警告: 已超过IP速率限制,拒绝请求 - 客户端IP: %s", clientIP)
|
||||||
|
SendJSONError(w, http.StatusTooManyRequests, "Rate limit exceeded. Please try again later.", "rate_limit_error", "rate_limit_exceeded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConcurrencyLimit(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
select {
|
||||||
|
case ConcurrencySem <- struct{}{}:
|
||||||
|
defer func() { <-ConcurrencySem }()
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
default:
|
||||||
|
log.Printf("警告: 已达到最大并发请求数限制,拒绝请求 - 客户端IP: %s", GetClientIP(r))
|
||||||
|
SendJSONError(w, http.StatusServiceUnavailable, "Server is busy, maximum concurrent requests reached. Please try again later.", "concurrency_limit_error", "max_concurrent_requests")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -13,6 +13,8 @@ func Setup() *mux.Router {
|
|||||||
|
|
||||||
r.Use(middleware.CORS)
|
r.Use(middleware.CORS)
|
||||||
r.Use(middleware.SecurityHeaders)
|
r.Use(middleware.SecurityHeaders)
|
||||||
|
r.Use(middleware.RateLimit)
|
||||||
|
r.Use(middleware.ConcurrencyLimit)
|
||||||
r.Use(middleware.Logger)
|
r.Use(middleware.Logger)
|
||||||
|
|
||||||
r.HandleFunc("/v1/audio/speech", controller.OpenaiTTSHandler).Methods("POST", "OPTIONS")
|
r.HandleFunc("/v1/audio/speech", controller.OpenaiTTSHandler).Methods("POST", "OPTIONS")
|
||||||
|
|||||||
Reference in New Issue
Block a user