首页 > 文章列表 > 使用 Echo Framework Golang 自定义配置时,我们可以在 CORSWithConfig 中设置中间件以指定参数和可接受的选项

使用 Echo Framework Golang 自定义配置时,我们可以在 CORSWithConfig 中设置中间件以指定参数和可接受的选项

318 2024-02-08
问题内容

参数是什么及其可接受的值,以及如何在中间件中使用 CORSWithConfig 自定义配置,同时在 golang 中使用 echo 框架来处理 CORS。


正确答案


其实还有很多其他的参数。您可以在此处阅读有关它们的信息。

配置

corsconfig struct {
  // skipper defines a function to skip middleware.
  skipper skipper

  // alloworigin defines a list of origins that may access the resource.
  // optional. default value []string{"*"}.
  alloworigins []string `yaml:"allow_origins"`

  // alloworiginfunc is a custom function to validate the origin. it takes the
  // origin as an argument and returns true if allowed or false otherwise. if
  // an error is returned, it is returned by the handler. if this option is
  // set, alloworigins is ignored.
  // optional.
  alloworiginfunc func(origin string) (bool, error) `yaml:"allow_origin_func"`

  // allowmethods defines a list methods allowed when accessing the resource.
  // this is used in response to a preflight request.
  // optional. default value defaultcorsconfig.allowmethods.
  allowmethods []string `yaml:"allow_methods"`

  // allowheaders defines a list of request headers that can be used when
  // making the actual request. this is in response to a preflight request.
  // optional. default value []string{}.
  allowheaders []string `yaml:"allow_headers"`

  // allowcredentials indicates whether or not the response to the request
  // can be exposed when the credentials flag is true. when used as part of
  // a response to a preflight request, this indicates whether or not the
  // actual request can be made using credentials.
  // optional. default value false.
  allowcredentials bool `yaml:"allow_credentials"`

  // exposeheaders defines a whitelist headers that clients are allowed to
  // access.
  // optional. default value []string{}.
  exposeheaders []string `yaml:"expose_headers"`

  // maxage indicates how long (in seconds) the results of a preflight request
  // can be cached.
  // optional. default value 0.
  maxage int `yaml:"max_age"`
}

使用示例

e := echo.new()
e.use(middleware.corswithconfig(middleware.corsconfig{
  alloworigins: []string{"https://labstack.com", "https://labstack.net"},
  allowheaders: []string{echo.headerorigin, echo.headercontenttype, 
echo.headeraccept},
}))

默认

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