CORS(访问控制) 中间件

CORS 中间件实现了 CORS 的标准。CORS 提供给 web 服务器跨站的访问控制,使得跨站的数据传输更安全。

使用

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

自定义配置

使用

  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. }))

配置

  1. // CORSConfig defines the config for CORS middleware.
  2. CORSConfig struct {
  3. // Skipper defines a function to skip middleware.
  4. Skipper Skipper
  5. // AllowOrigin defines a list of origins that may access the resource.
  6. // Optional. Default value []string{"*"}.
  7. AllowOrigins []string `json:"allow_origins"`
  8. // AllowMethods defines a list methods allowed when accessing the resource.
  9. // This is used in response to a preflight request.
  10. // Optional. Default value DefaultCORSConfig.AllowMethods.
  11. AllowMethods []string `json:"allow_methods"`
  12. // AllowHeaders defines a list of request headers that can be used when
  13. // making the actual request. This in response to a preflight request.
  14. // Optional. Default value []string{}.
  15. AllowHeaders []string `json:"allow_headers"`
  16. // AllowCredentials indicates whether or not the response to the request
  17. // can be exposed when the credentials flag is true. When used as part of
  18. // a response to a preflight request, this indicates whether or not the
  19. // actual request can be made using credentials.
  20. // Optional. Default value false.
  21. AllowCredentials bool `json:"allow_credentials"`
  22. // ExposeHeaders defines a whitelist headers that clients are allowed to
  23. // access.
  24. // Optional. Default value []string{}.
  25. ExposeHeaders []string `json:"expose_headers"`
  26. // MaxAge indicates how long (in seconds) the results of a preflight request
  27. // can be cached.
  28. // Optional. Default value 0.
  29. MaxAge int `json:"max_age"`
  30. }

默认配置

  1. DefaultCORSConfig = CORSConfig{
  2. Skipper: defaultSkipper,
  3. AllowOrigins: []string{"*"},
  4. AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
  5. }