-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package middlewares | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/tangx/rum-gonic/rum" | ||
) | ||
|
||
// DefaultCorsPolicy 默认跨域规则, 所有来源 | ||
func DefaultCorsPolicy() rum.MiddlewareOperator { | ||
return CorsPolicy("*") | ||
} | ||
|
||
// CorsPolicy 允许跨域来源 | ||
// example, sorigin = https://developer.mozilla.org | ||
func CorsPolicy(origin string) rum.MiddlewareOperator { | ||
|
||
cors := func(c *gin.Context) { | ||
method := c.Request.Method | ||
if method != "" { | ||
c.Header("Access-Control-Allow-Origin", 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-Token") | ||
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() | ||
} | ||
|
||
return rum.NewMiddleware(cors) | ||
} |