starter/biz/middleware/cors.go
2026-03-28 19:29:40 +08:00

25 lines
727 B
Go

package middleware
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
)
func CorsMiddleware() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
origin := ctx.Request.Header.Get("Origin")
ctx.Header("Access-Control-Allow-Origin", ctx.Request.Header.Get("origin"))
if origin != "" {
ctx.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
ctx.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,Authorization,Cookie,FTF-Cookie-accessToken, x-origin")
ctx.Header("Access-Control-Allow-Credentials", "true")
}
method := ctx.Request.Method()
if string(method) == "OPTIONS" {
ctx.AbortWithStatus(200)
}
ctx.Next(c)
}
}