This commit is contained in:
2025-08-28 00:50:30 +08:00
parent 5051aea55c
commit 50a4fa86ce
2 changed files with 28 additions and 11 deletions

View File

@@ -228,9 +228,9 @@ development:
debug: true debug: true
enable_profiler: true enable_profiler: true
enable_cors: true enable_cors: true
cors_allowed_origins: "http://localhost:3000,http://localhost:3001" cors_allowed_origins: "https://consoletest.tianyuanapi.com,https://console.tianyuanapi.com"
cors_allowed_methods: "GET,POST,PUT,PATCH,DELETE,OPTIONS" cors_allowed_methods: "GET,POST,PUT,PATCH,DELETE,OPTIONS"
cors_allowed_headers: "Origin,Content-Type,Accept,Authorization,X-Requested-With" cors_allowed_headers: "Origin,Content-Type,Accept,Authorization,X-Requested-With,Access-Id"
# 企业微信配置 # 企业微信配置
wechat_work: wechat_work:

View File

@@ -1,6 +1,7 @@
package middleware package middleware
import ( import (
"strings"
"tyapi-server/internal/config" "tyapi-server/internal/config"
"github.com/gin-contrib/cors" "github.com/gin-contrib/cors"
@@ -67,8 +68,13 @@ func (m *CORSMiddleware) getAllowedOrigins() []string {
return []string{"http://localhost:3000", "http://localhost:8080"} return []string{"http://localhost:3000", "http://localhost:8080"}
} }
// TODO: 解析配置中的origins字符串 // 解析配置中的origins字符串,按逗号分隔
return []string{m.config.Development.CorsOrigins} origins := strings.Split(m.config.Development.CorsOrigins, ",")
// 去除空格
for i, origin := range origins {
origins[i] = strings.TrimSpace(origin)
}
return origins
} }
// getAllowedMethods 获取允许的方法 // getAllowedMethods 获取允许的方法
@@ -79,8 +85,13 @@ func (m *CORSMiddleware) getAllowedMethods() []string {
} }
} }
// TODO: 解析配置中的methods字符串 // 解析配置中的methods字符串,按逗号分隔
return []string{m.config.Development.CorsMethods} methods := strings.Split(m.config.Development.CorsMethods, ",")
// 去除空格
for i, method := range methods {
methods[i] = strings.TrimSpace(method)
}
return methods
} }
// getAllowedHeaders 获取允许的头部 // getAllowedHeaders 获取允许的头部
@@ -88,17 +99,23 @@ func (m *CORSMiddleware) getAllowedHeaders() []string {
if m.config.Development.CorsHeaders == "" { if m.config.Development.CorsHeaders == "" {
return []string{ return []string{
"Origin", "Origin",
"Content-Length",
"Content-Type", "Content-Type",
"Authorization", "Content-Length",
"X-Requested-With",
"Accept", "Accept",
"Accept-Encoding", "Accept-Encoding",
"Accept-Language", "Accept-Language",
"Authorization",
"X-Requested-With",
"X-Request-ID", "X-Request-ID",
"Access-Id",
} }
} }
// TODO: 解析配置中的headers字符串 // 解析配置中的headers字符串,按逗号分隔
return []string{m.config.Development.CorsHeaders} headers := strings.Split(m.config.Development.CorsHeaders, ",")
// 去除空格
for i, header := range headers {
headers[i] = strings.TrimSpace(header)
}
return headers
} }