cors.go 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/gin-gonic/gin"
  7. )
  8. // CORS 跨域
  9. func CORS() gin.HandlerFunc {
  10. return func(c *gin.Context) {
  11. method := c.Request.Method //请求方法
  12. origin := c.Request.Header.Get("Origin") //请求头部
  13. var headerKeys []string // 声明请求头keys
  14. for k, _ := range c.Request.Header {
  15. headerKeys = append(headerKeys, k)
  16. }
  17. headerStr := strings.Join(headerKeys, ", ")
  18. if headerStr != "" {
  19. headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
  20. } else {
  21. headerStr = "access-control-allow-origin, access-control-allow-headers"
  22. }
  23. if origin != "" {
  24. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  25. c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
  26. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
  27. // header的类型
  28. c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, id, Token, name, optname, thumbnail, 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")
  29. // 允许跨域设置 可以返回其他子段
  30. 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") // 跨域关键设置 让浏览器可以解析
  31. c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
  32. c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
  33. c.Set("content-type", "application/json") // 设置返回格式是json
  34. }
  35. //放行所有OPTIONS方法
  36. if method == "OPTIONS" {
  37. c.JSON(http.StatusOK, "Options Request!")
  38. }
  39. // 处理请求
  40. c.Next() // 处理请求
  41. }
  42. }