fix duplicated cors headers

This commit is contained in:
2024-01-04 19:03:58 +08:00
parent 9fdbf259c0
commit 2bbe98e694
3 changed files with 29 additions and 4 deletions

15
cors.go
View File

@@ -4,10 +4,19 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// this function is aborded
func corsMiddleware() gin.HandlerFunc { func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*") // set cors header
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH") header := c.Request.Header
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type") if header.Get("Access-Control-Allow-Origin") == "" {
c.Header("Access-Control-Allow-Origin", "*")
}
if header.Get("Access-Control-Allow-Methods") == "" {
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
}
if header.Get("Access-Control-Allow-Headers") == "" {
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
}
} }
} }

View File

@@ -74,7 +74,7 @@ func main() {
m.Use(engine) m.Use(engine)
// CORS middleware // CORS middleware
engine.Use(corsMiddleware()) // engine.Use(corsMiddleware())
// error handle middleware // error handle middleware
engine.Use(func(c *gin.Context) { engine.Use(func(c *gin.Context) {
@@ -90,6 +90,10 @@ func main() {
// CORS handler // CORS handler
engine.OPTIONS("/v1/*any", func(ctx *gin.Context) { engine.OPTIONS("/v1/*any", func(ctx *gin.Context) {
// set cros header
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
ctx.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
ctx.AbortWithStatus(200) ctx.AbortWithStatus(200)
}) })

View File

@@ -110,6 +110,18 @@ func processRequest(c *gin.Context, upstream *OPENAI_UPSTREAM, record *Record, s
haveResponse = true haveResponse = true
record.ResponseTime = time.Now().Sub(record.CreatedAt) record.ResponseTime = time.Now().Sub(record.CreatedAt)
record.Status = r.StatusCode record.Status = r.StatusCode
// handle reverse proxy cors header if upstream do not set that
if r.Header.Get("Access-Control-Allow-Origin") == "" {
c.Header("Access-Control-Allow-Origin", "*")
}
if r.Header.Get("Access-Control-Allow-Methods") == "" {
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
}
if r.Header.Get("Access-Control-Allow-Headers") == "" {
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
}
if !shouldResponse && r.StatusCode != 200 { if !shouldResponse && r.StatusCode != 200 {
log.Println("upstream return not 200 and should not response", r.StatusCode) log.Println("upstream return not 200 and should not response", r.StatusCode)
return errors.New("upstream return not 200 and should not response") return errors.New("upstream return not 200 and should not response")