
本文详解如何在使用 Kami 路由框架的 Go 服务中安全、合规地启用跨域资源共享(CORS),重点解决带凭据(Basic Auth)请求下的预检失败、Origin 头缺失、Access-Control-Allow-Origin 冲突等典型问题。
本文详解如何在使用 kami 路由框架的 go 服务中安全、合规地启用跨域资源共享(cors),重点解决带凭据(basic auth)请求下的预检失败、origin 头缺失、access-control-allow-origin 冲突等典型问题。
在前后端分离开发中,React 应用运行于 http://localhost:3000,而 Go 后端(基于 Kami)监听 http://localhost:8000,此时浏览器因同源策略拦截请求,并抛出经典错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
尤其当后端启用 Basic Auth(如 http://user:password@localhost:8000/...)时,请求自动携带凭据(credentials: 'include'),此时 *`Access-Control-Allow-Origin: ""将被浏览器静默拒绝**——这是硬性安全限制,必须改用明确的白名单域名并配合AllowCredentials: true`。
✅ 正确集成 rs/cors 与 Kami
Kami 本身不内置 CORS 中间件,但支持通过 kami.Use(prefix, handler) 注册任意 http.Handler 作为中间件。rs/cors 正是为此场景设计的成熟方案。关键在于:不能将 CORS 包裹整个 kami.Serve(),而应精准作用于 API 路径前缀(如 /api/),避免干扰静态资源或健康检查端点。
以下是完整、可直接复用的集成方案:
import (
"context"
"log"
"net/http"
"os"
"github.com/guregu/kami"
"github.com/rs/cors"
"gopkg.in/mgo.v2"
)
func main() {
session, err := mgo.Dial(mongoURI())
if err != nil {
log.Fatal(err)
}
defer session.Close()
systemsC := session.DB("").C("systems")
flag.Parse()
ctx := context.Background()
kami.Context = ctx
// ✅ Step 1: 配置 CORS 中间件(仅限 /api/ 路径)
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"}, // 开发环境明确指定;生产建议动态校验
AllowCredentials: true, // 必须为 true 才能支持 Basic Auth
AllowedMethods: []string{
http.MethodGet, http.MethodPost,
http.MethodDelete, http.MethodOptions, // 显式包含 OPTIONS!
},
AllowedHeaders: []string{
"Accept", "Content-Type", "Authorization",
"X-CSRF-Token", "X-Requested-With",
},
// ✅ 自动处理预检请求:OptionsPassthrough 默认 false,已拦截
// ✅ 自动添加 Vary: Origin 头(满足规范)
})
// ✅ Step 2: 将 CORS 中间件挂载到 /api/ 前缀(顺序关键!)
kami.Use("/api/", c.Handler)
// ✅ Step 3: Basic Auth 中间件(必须放在 CORS 之后!否则预检无法通过)
kami.Use("/api/", httpauth.SimpleBasicAuth(
os.Getenv("BASIC_USERNAME"),
os.Getenv("BASIC_PASSWORD"),
))
// ✅ Step 4: 定义路由(无需手动写 CORS 头!)
kami.Get("/api/v1/systems", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
systems := []alpha.System{}
systemsMap := map[string][]alpha.System{}
if err := systemsC.Find(nil).All(&systems); err != nil {
log.Println("DB error:", err)
http.Error(w, err.Error(), http.StatusNotFound)
return
}
systemsMap["systems"] = systems
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(&systemsMap); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
log.Println("Server starting on :8000...")
kami.Serve()
}
⚠️ 关键注意事项
-
中间件顺序不可颠倒:
kami.Use("/api/", c.Handler)必须在httpauth.SimpleBasicAuth(...)之前注册。否则预检请求(OPTIONS)会先被鉴权中间件拦截并返回 401,导致浏览器收不到 CORS 响应头。 - *
AllowedOrigins严禁使用 `""+AllowCredentials: true**:这会导致响应被浏览器丢弃。开发阶段可固定为[]string{"http://localhost:3000"}`;生产环境务必改为动态白名单(例如从配置中心读取或解析Origin请求头后校验)。 -
OPTIONS请求必须由 CORS 中间件拦截:rs/cors默认OptionsPassthrough: false,会主动响应 204 状态码且空响应体——这是符合规范的正确行为。若误设为true,则 OPTIONS 会被转发给下游(此处即 Kami 路由),而 Kami 未注册 OPTIONS 路由,必然返回 404,引发preflight request doesn't pass access control check错误。 -
前端 fetch 必须显式声明 credentials:
fetch('http://localhost:8000/api/v1/systems', { credentials: 'include' // ← 必须与后端 AllowCredentials: true 匹配 })
? 进阶建议:生产环境动态 Origin 校验
对于多租户、灰度发布等场景,硬编码 AllowedOrigins 维护成本高且不安全。推荐使用 rs/cors 的 AllowedOriginsFunc 回调:
c := cors.New(cors.Options{
AllowedOriginsFunc: func(origin string) bool {
// 示例:从 Redis 或数据库查询白名单
// return isInWhitelist(origin)
return origin == "https://prod.example.com" ||
origin == "https://staging.example.com"
},
AllowCredentials: true,
// ... 其他选项
})
这样既满足安全性要求,又具备灵活的运维能力。
至此,你的 Kami 服务已具备健壮、合规的 CORS 支持,可安全承载带凭据的跨域请求,彻底告别 No 'Access-Control-Allow-Origin' header 报错。











