ソースを参照

feat(middlewares): cors 中间件

runningwater 7 ヶ月 前
コミット
ec58ab8513
3 ファイル変更30 行追加0 行削除
  1. 2 0
      README.md
  2. 26 0
      app/http/middlewares/cors.go
  3. 2 0
      bootstrap/route.go

+ 2 - 0
README.md

@@ -72,6 +72,8 @@ UNIQUE KEY `migration` (`migration`)
 
 #### 🚀 新功能
 
+- *(middlewares)* Cors 中间件
+- Migrate 包
 - *(command)* Make request 命令
 - *(command)* Make apicontroller 命令
 - 限流中间件

+ 26 - 0
app/http/middlewares/cors.go

@@ -0,0 +1,26 @@
+package middlewares
+
+import (
+	"net/http"
+
+	"github.com/gin-gonic/gin"
+)
+
+func Cors() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		method := c.Request.Method
+		origin := c.Request.Header.Get("Origin")
+		if origin != "" {
+			c.Header("Access-Control-Allow-Origin", "*")
+			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
+			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After")
+			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
+			c.Header("Access-Control-Allow-Credentials", "true")
+		}
+		if method == "OPTIONS" {
+			c.AbortWithStatus(http.StatusNoContent)
+		}
+
+		c.Next()
+	}
+}

+ 2 - 0
bootstrap/route.go

@@ -40,5 +40,7 @@ func registerGlobalMiddleWare(router *gin.Engine) {
 	router.Use(
 		middlewares.Logger(),
 		middlewares.Recovery(),
+		middlewares.Cors(),
+		// middlewares.LimitIP("1000-H"),
 	)
 }