CORS跨域资源共享控制
HTTP Dispatcher
的入口路由组特性,可以很方便的开发一个CORS处理器并在入口路由组执行。
CORS处理函数
- //CORS配置
- type CORSconfig struct {
- AllowOrigins []string
- ExposeHeaders []string
- AllowCredentials bool
- AllowMethods []string
- AllowHeaders []string
- }
- //CORS处理器
- func CORSHandler(config *CORSconfig) httpdispatcher.Handler {
- return func(ctx *httpdispatcher.Context) error {
- if config.AllowOrigins != nil {
- if config.AllowMethods[0] == "*" {
- ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
- } else {
- ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", strings.Join(config.AllowOrigins, ","))
- }
- }
- if config.AllowMethods != nil {
- if config.AllowMethods[0] == "*" {
- ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "*")
- } else {
- ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", strings.Join(config.AllowMethods, ","))
- }
- }
- if config.AllowHeaders != nil {
- if config.AllowHeaders[0] == "*" {
- ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")
- } else {
- ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", strings.Join(config.AllowHeaders, ","))
- }
- }
- if config.ExposeHeaders != nil {
- if config.ExposeHeaders[0] == "*" {
- ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", "*")
- } else {
- ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", strings.Join(config.ExposeHeaders, ","))
- }
- }
- if config.ExposeHeaders != nil {
- if config.ExposeHeaders[0] == "*" {
- ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", "*")
- } else {
- ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", strings.Join(config.ExposeHeaders, ","))
- }
- }
- if config.AllowCredentials == true {
- ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
- }
- //继续执行路由函数
- return ctx.Next(true)
- }
- }
使用CORS处理器
- //获得一个调度器的实例化对象
- var dispatcher = httpdispatcher.New()
- //定义CORS的配置
- var corsConfig CORSconfig
- corsConfig.AllowOrigins=[]string{"*"}
- corsConfig.AllowMethods=[]string{"*"}
- corsConfig.AllowHeaders=[]string{"*"}
- corsConfig.AllowCredentials=true
- corsConfig.ExposeHeaders=[]string{"*"}
- //注册入口路由组,并传入CORS处理器
- router := dispatcher.Router.GROUP("", CORSHandler(&corsConfig))
- //在路由组里注册路由,会自动执行CORS处理器
- router.GET("/", func(ctx *httpdispatcher.Context) error {
- return nil
- })