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"
)
// this function is aborded
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
// set cors header
header := c.Request.Header
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)
// CORS middleware
engine.Use(corsMiddleware())
// engine.Use(corsMiddleware())
// error handle middleware
engine.Use(func(c *gin.Context) {
@@ -90,6 +90,10 @@ func main() {
// CORS handler
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)
})

View File

@@ -110,6 +110,18 @@ func processRequest(c *gin.Context, upstream *OPENAI_UPSTREAM, record *Record, s
haveResponse = true
record.ResponseTime = time.Now().Sub(record.CreatedAt)
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 {
log.Println("upstream return not 200 and should not response", r.StatusCode)
return errors.New("upstream return not 200 and should not response")