cors.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package lxcors
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. "strings"
  7. )
  8. func Cors() gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. method := c.Request.Method
  11. //origin := c.Request.Header.Get("Origin")
  12. //fmt.Println("origin----", origin)
  13. var headerKeys []string
  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, Content-Type, %s", headerStr)
  20. } else {
  21. headerStr = "access-control-allow-origin, access-control-allow-headers"
  22. }
  23. headerStr += "access-control-allow-origin, access-control-allow-headers, Content-Type,token"
  24. //var origins = []string{"https://www.qizhangfang.com", "https://wx.qizhangfang.net", "https://qizhangfang.com", "http://www.qizhangfang.com", "http://qizhangfang.com",
  25. // "http://192.168.3.153:8000", "http://localhost:8000"} // 允许跨域
  26. //fmt.Println(origins)
  27. //if origin != "" {
  28. //
  29. //
  30. //}
  31. //下面的都是乱添加的-_-~
  32. //c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  33. //c.Header("Access-Control-Allow-Origin", ogn)
  34. c.Header("Access-Control-Allow-Origin", "*")
  35. c.Header("Access-Control-Allow-Headers", headerStr)
  36. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
  37. // c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, 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")
  38. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, Token, token")
  39. // c.Header("Access-Control-Max-Age", "172800")
  40. c.Header("Access-Control-Allow-Credentials", "true")
  41. c.Set("content-type", "application/json")
  42. //放行所有OPTIONS方法
  43. if method == "OPTIONS" {
  44. c.JSON(http.StatusOK, "Options Request!")
  45. }
  46. c.Next()
  47. }
  48. }