CORS

CORS middleware implements CORS specification. CORS gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

Usage

  1. e.Use(middleware.CORS())

Custom Configuration

Usage

  1. e := echo.New()
  2. e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
  3. AllowOrigins: []string{"https://labstack.com", "https://labstack.net"},
  4. AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
  5. }))

Configuration

  1. CORSConfig struct {
  2. // Skipper defines a function to skip middleware.
  3. Skipper Skipper
  4. // AllowOrigin defines a list of origins that may access the resource.
  5. // Optional. Default value []string{"*"}.
  6. AllowOrigins []string `yaml:"allow_origins"`
  7. // AllowOriginFunc is a custom function to validate the origin. It takes the
  8. // origin as an argument and returns true if allowed or false otherwise. If
  9. // an error is returned, it is returned by the handler. If this option is
  10. // set, AllowOrigins is ignored.
  11. // Optional.
  12. AllowOriginFunc func(origin string) (bool, error) `yaml:"allow_origin_func"`
  13. // AllowMethods defines a list methods allowed when accessing the resource.
  14. // This is used in response to a preflight request.
  15. // Optional. Default value DefaultCORSConfig.AllowMethods.
  16. AllowMethods []string `yaml:"allow_methods"`
  17. // AllowHeaders defines a list of request headers that can be used when
  18. // making the actual request. This is in response to a preflight request.
  19. // Optional. Default value []string{}.
  20. AllowHeaders []string `yaml:"allow_headers"`
  21. // AllowCredentials indicates whether or not the response to the request
  22. // can be exposed when the credentials flag is true. When used as part of
  23. // a response to a preflight request, this indicates whether or not the
  24. // actual request can be made using credentials.
  25. // Optional. Default value false.
  26. AllowCredentials bool `yaml:"allow_credentials"`
  27. // ExposeHeaders defines a whitelist headers that clients are allowed to
  28. // access.
  29. // Optional. Default value []string{}.
  30. ExposeHeaders []string `yaml:"expose_headers"`
  31. // MaxAge indicates how long (in seconds) the results of a preflight request
  32. // can be cached.
  33. // Optional. Default value 0.
  34. MaxAge int `yaml:"max_age"`
  35. }

Default Configuration

  1. DefaultCORSConfig = CORSConfig{
  2. Skipper: DefaultSkipper,
  3. AllowOrigins: []string{"*"},
  4. AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
  5. }