use cors middleware
This commit is contained in:
19
cors.go
Normal file
19
cors.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func corsMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// delete existing headers
|
||||
c.Writer.Header().Del("Access-Control-Allow-Origin")
|
||||
c.Writer.Header().Del("Access-Control-Allow-Methods")
|
||||
c.Writer.Header().Del("Access-Control-Allow-Headers")
|
||||
|
||||
// set new headers
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
|
||||
}
|
||||
}
|
||||
7
main.go
7
main.go
@@ -85,12 +85,11 @@ func main() {
|
||||
})
|
||||
})
|
||||
|
||||
// CORS middleware
|
||||
engine.Use(corsMiddleware())
|
||||
|
||||
// CORS handler
|
||||
engine.OPTIONS("/v1/*any", func(ctx *gin.Context) {
|
||||
header := ctx.Writer.Header()
|
||||
header.Set("Access-Control-Allow-Origin", "*")
|
||||
header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
|
||||
header.Set("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
|
||||
ctx.AbortWithStatus(200)
|
||||
})
|
||||
|
||||
|
||||
@@ -113,12 +113,6 @@ func processRequest(c *gin.Context, upstream *OPENAI_UPSTREAM, record *Record, s
|
||||
log.Println("upstream return not 200 and should not response", r.StatusCode)
|
||||
return errors.New("upstream return not 200 and should not response")
|
||||
}
|
||||
r.Header.Del("Access-Control-Allow-Origin")
|
||||
r.Header.Del("Access-Control-Allow-Methods")
|
||||
r.Header.Del("Access-Control-Allow-Headers")
|
||||
r.Header.Set("Access-Control-Allow-Origin", "*")
|
||||
r.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
|
||||
r.Header.Set("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
|
||||
|
||||
if r.StatusCode != 200 {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
|
||||
Reference in New Issue
Block a user