fix duplicated cors headers
This commit is contained in:
9
cors.go
9
cors.go
@@ -4,10 +4,19 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// this function is aborded
|
||||
func corsMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
6
main.go
6
main.go
@@ -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)
|
||||
})
|
||||
|
||||
|
||||
12
process.go
12
process.go
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user