Skip to content

Commit

Permalink
Add CORS middleware to handle cross-origin requests
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaozhou26 committed Apr 4, 2024
1 parent ce472a8 commit 1a2af1d
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,23 @@ func init() {
readAccessToken()
}

func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")

// 如果是OPTIONS请求,直接返回
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}

c.Next()
}
}

func checkProxy() {
proxies := []string{}
PROXY_URL := os.Getenv("PROXY_URL")
Expand Down Expand Up @@ -80,8 +97,7 @@ func checkProxy() {

func main() {
router := gin.Default()

router.Use(cors)
router.Use(CORSMiddleware())

router.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
Expand Down

0 comments on commit 1a2af1d

Please sign in to comment.