cors.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package cors
  2. import (
  3. "errors"
  4. "strings"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. )
  8. // Config represents all available options for the middleware.
  9. type Config struct {
  10. AllowAllOrigins bool
  11. // AllowOrigins is a list of origins a cross-domain request can be executed from.
  12. // If the special "*" value is present in the list, all origins will be allowed.
  13. // Default value is []
  14. AllowOrigins []string
  15. // AllowOriginFunc is a custom function to validate the origin. It take the origin
  16. // as argument and returns true if allowed or false otherwise. If this option is
  17. // set, the content of AllowOrigins is ignored.
  18. AllowOriginFunc func(origin string) bool
  19. // AllowMethods is a list of methods the client is allowed to use with
  20. // cross-domain requests. Default value is simple methods (GET and POST)
  21. AllowMethods []string
  22. // AllowHeaders is list of non simple headers the client is allowed to use with
  23. // cross-domain requests.
  24. AllowHeaders []string
  25. // AllowCredentials indicates whether the request can include user credentials like
  26. // cookies, HTTP authentication or client side SSL certificates.
  27. AllowCredentials bool
  28. // ExposedHeaders indicates which headers are safe to expose to the API of a CORS
  29. // API specification
  30. ExposeHeaders []string
  31. // MaxAge indicates how long (in seconds) the results of a preflight request
  32. // can be cached
  33. MaxAge time.Duration
  34. // Allows to add origins like http://some-domain/*, https://api.* or http://some.*.subdomain.com
  35. AllowWildcard bool
  36. // Allows usage of popular browser extensions schemas
  37. AllowBrowserExtensions bool
  38. // Allows usage of WebSocket protocol
  39. AllowWebSockets bool
  40. // Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed
  41. AllowFiles bool
  42. }
  43. // AddAllowMethods is allowed to add custom methods
  44. func (c *Config) AddAllowMethods(methods ...string) {
  45. c.AllowMethods = append(c.AllowMethods, methods...)
  46. }
  47. // AddAllowHeaders is allowed to add custom headers
  48. func (c *Config) AddAllowHeaders(headers ...string) {
  49. c.AllowHeaders = append(c.AllowHeaders, headers...)
  50. }
  51. // AddExposeHeaders is allowed to add custom expose headers
  52. func (c *Config) AddExposeHeaders(headers ...string) {
  53. c.ExposeHeaders = append(c.ExposeHeaders, headers...)
  54. }
  55. func (c Config) getAllowedSchemas() []string {
  56. allowedSchemas := DefaultSchemas
  57. if c.AllowBrowserExtensions {
  58. allowedSchemas = append(allowedSchemas, ExtensionSchemas...)
  59. }
  60. if c.AllowWebSockets {
  61. allowedSchemas = append(allowedSchemas, WebSocketSchemas...)
  62. }
  63. if c.AllowFiles {
  64. allowedSchemas = append(allowedSchemas, FileSchemas...)
  65. }
  66. return allowedSchemas
  67. }
  68. func (c Config) validateAllowedSchemas(origin string) bool {
  69. allowedSchemas := c.getAllowedSchemas()
  70. for _, schema := range allowedSchemas {
  71. if strings.HasPrefix(origin, schema) {
  72. return true
  73. }
  74. }
  75. return false
  76. }
  77. // Validate is check configuration of user defined.
  78. func (c *Config) Validate() error {
  79. if c.AllowAllOrigins && (c.AllowOriginFunc != nil || len(c.AllowOrigins) > 0) {
  80. return errors.New("conflict settings: all origins are allowed. AllowOriginFunc or AllowOrigins is not needed")
  81. }
  82. if !c.AllowAllOrigins && c.AllowOriginFunc == nil && len(c.AllowOrigins) == 0 {
  83. return errors.New("conflict settings: all origins disabled")
  84. }
  85. for _, origin := range c.AllowOrigins {
  86. if origin == "*" {
  87. c.AllowAllOrigins = true
  88. return nil
  89. } else if !strings.Contains(origin, "*") && !c.validateAllowedSchemas(origin) {
  90. return errors.New("bad origin: origins must contain '*' or include " + strings.Join(c.getAllowedSchemas(), ","))
  91. }
  92. }
  93. return nil
  94. }
  95. func (c Config) parseWildcardRules() [][]string {
  96. var wRules [][]string
  97. if !c.AllowWildcard {
  98. return wRules
  99. }
  100. for _, o := range c.AllowOrigins {
  101. if !strings.Contains(o, "*") {
  102. continue
  103. }
  104. if c := strings.Count(o, "*"); c > 1 {
  105. panic(errors.New("only one * is allowed").Error())
  106. }
  107. i := strings.Index(o, "*")
  108. if i == 0 {
  109. wRules = append(wRules, []string{"*", o[1:]})
  110. continue
  111. }
  112. if i == (len(o) - 1) {
  113. wRules = append(wRules, []string{o[:i-1], "*"})
  114. continue
  115. }
  116. wRules = append(wRules, []string{o[:i], o[i+1:]})
  117. }
  118. return wRules
  119. }
  120. // DefaultConfig returns a generic default configuration mapped to localhost.
  121. func DefaultConfig() Config {
  122. return Config{
  123. AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
  124. AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"},
  125. AllowCredentials: false,
  126. MaxAge: 12 * time.Hour,
  127. }
  128. }
  129. // Default returns the location middleware with default configuration.
  130. func Default() gin.HandlerFunc {
  131. config := DefaultConfig()
  132. config.AllowAllOrigins = true
  133. return New(config)
  134. }
  135. // New returns the location middleware with user-defined custom configuration.
  136. func New(config Config) gin.HandlerFunc {
  137. cors := newCors(config)
  138. return func(c *gin.Context) {
  139. cors.applyCors(c)
  140. }
  141. }