Skip to content

Commit

Permalink
add cors for open api
Browse files Browse the repository at this point in the history
  • Loading branch information
zmh-program committed Oct 2, 2023
1 parent 1bae9b4 commit becb813
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,27 @@ import (
"chat/utils"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)

func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// open api for all origins
if strings.HasPrefix(c.Request.URL.Path, "/v1") {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

if c.Request.Method == "OPTIONS" {
c.Writer.Header().Set("Access-Control-Max-Age", "7200")
c.AbortWithStatus(http.StatusOK)
return
}
c.Next()
return
}

origin := c.Request.Header.Get("Origin")
if utils.Contains(origin, globals.AllowedOrigins) {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
Expand Down

0 comments on commit becb813

Please sign in to comment.