cors.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "lcfns/config"
  5. "lcfns/global"
  6. "net/http"
  7. )
  8. // Cors 直接放行所有跨域请求并放行所有 OPTIONS 方法
  9. func Cors() gin.HandlerFunc {
  10. return func(c *gin.Context) {
  11. method := c.Request.Method
  12. origin := c.Request.Header.Get("Origin")
  13. c.Header("Access-Control-Allow-Origin", origin)
  14. c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
  15. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
  16. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At")
  17. c.Header("Access-Control-Allow-Credentials", "true")
  18. // 放行所有OPTIONS方法
  19. if method == "OPTIONS" {
  20. c.AbortWithStatus(http.StatusNoContent)
  21. }
  22. // 处理请求
  23. c.Next()
  24. }
  25. }
  26. // CorsByRules 按照配置处理跨域请求
  27. func CorsByRules() gin.HandlerFunc {
  28. // 放行全部
  29. if global.Config.Cors.Mode == "allow-all" {
  30. return Cors()
  31. }
  32. return func(c *gin.Context) {
  33. whitelist := checkCors(c.GetHeader("origin"))
  34. // 通过检查, 添加请求头
  35. if whitelist != nil {
  36. c.Header("Access-Control-Allow-Origin", whitelist.AllowOrigin)
  37. c.Header("Access-Control-Allow-Headers", whitelist.AllowHeaders)
  38. c.Header("Access-Control-Allow-Methods", whitelist.AllowMethods)
  39. c.Header("Access-Control-Expose-Headers", whitelist.ExposeHeaders)
  40. if whitelist.AllowCredentials {
  41. c.Header("Access-Control-Allow-Credentials", "true")
  42. }
  43. }
  44. // 严格白名单模式且未通过检查,直接拒绝处理请求
  45. if whitelist == nil && global.Config.Cors.Mode == "strict-whitelist" && !(c.Request.Method == "GET" && c.Request.URL.Path == "/health") {
  46. c.AbortWithStatus(http.StatusForbidden)
  47. } else {
  48. // 非严格白名单模式,无论是否通过检查均放行所有 OPTIONS 方法
  49. if c.Request.Method == http.MethodOptions {
  50. c.AbortWithStatus(http.StatusNoContent)
  51. }
  52. }
  53. // 处理请求
  54. c.Next()
  55. }
  56. }
  57. func checkCors(currentOrigin string) *config.CORSWhitelist {
  58. for _, whitelist := range global.Config.Cors.Whitelist {
  59. // 遍历配置中的跨域头,寻找匹配项
  60. if currentOrigin == whitelist.AllowOrigin {
  61. return &whitelist
  62. }
  63. }
  64. return nil
  65. }