广告平台(站长下代理使用)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mw_cors.go 1.5 KiB

3 months ago
1234567891011121314151617181920212223242526272829
  1. package mw
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. // cors跨域
  6. func Cors(c *gin.Context) {
  7. // 放行所有OPTIONS方法
  8. if c.Request.Method == "OPTIONS" {
  9. c.AbortWithStatus(204)
  10. return
  11. }
  12. origin := c.Request.Header.Get("Origin") // 请求头部
  13. if origin != "" {
  14. c.Header("Access-Control-Allow-Origin", origin) // 这是允许访问来源域
  15. c.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE,UPDATE") // 服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
  16. // header的类型
  17. c.Header("Access-Control-Allow-Headers", "Authorization,Content-Length,X-CSRF-Token,Token,session,X_Requested_With,Accept,Origin,Host,Connection,Accept-Encoding,Accept-Language,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Pragma,X-Mx-ReqToken")
  18. // 允许跨域设置,可以返回其他子段
  19. // 跨域关键设置 让浏览器可以解析
  20. c.Header("Access-Control-Expose-Headers", "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
  21. c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
  22. c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
  23. c.Set("Content-Type", "Application/json") // 设置返回格式是json
  24. }
  25. c.Next()
  26. }