CORS跨域资源共享控制

HTTP Dispatcher的入口路由组特性,可以很方便的开发一个CORS处理器并在入口路由组执行。

CORS处理函数

  1. //CORS配置
  2. type CORSconfig struct {
  3. AllowOrigins []string
  4. ExposeHeaders []string
  5. AllowCredentials bool
  6. AllowMethods []string
  7. AllowHeaders []string
  8. }
  9.  
  10. //CORS处理器
  11. func CORSHandler(config *CORSconfig) httpdispatcher.Handler {
  12. return func(ctx *httpdispatcher.Context) error {
  13. if config.AllowOrigins != nil {
  14. if config.AllowMethods[0] == "*" {
  15. ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
  16. } else {
  17. ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", strings.Join(config.AllowOrigins, ","))
  18. }
  19. }
  20. if config.AllowMethods != nil {
  21. if config.AllowMethods[0] == "*" {
  22. ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "*")
  23. } else {
  24. ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", strings.Join(config.AllowMethods, ","))
  25. }
  26. }
  27. if config.AllowHeaders != nil {
  28. if config.AllowHeaders[0] == "*" {
  29. ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")
  30. } else {
  31. ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", strings.Join(config.AllowHeaders, ","))
  32. }
  33. }
  34. if config.ExposeHeaders != nil {
  35. if config.ExposeHeaders[0] == "*" {
  36. ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", "*")
  37. } else {
  38. ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", strings.Join(config.ExposeHeaders, ","))
  39. }
  40. }
  41. if config.ExposeHeaders != nil {
  42. if config.ExposeHeaders[0] == "*" {
  43. ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", "*")
  44. } else {
  45. ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", strings.Join(config.ExposeHeaders, ","))
  46. }
  47. }
  48. if config.AllowCredentials == true {
  49. ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
  50. }
  51. //继续执行路由函数
  52. return ctx.Next(true)
  53. }
  54. }

使用CORS处理器

  1. //获得一个调度器的实例化对象
  2. var dispatcher = httpdispatcher.New()
  3.  
  4. //定义CORS的配置
  5. var corsConfig CORSconfig
  6. corsConfig.AllowOrigins=[]string{"*"}
  7. corsConfig.AllowMethods=[]string{"*"}
  8. corsConfig.AllowHeaders=[]string{"*"}
  9. corsConfig.AllowCredentials=true
  10. corsConfig.ExposeHeaders=[]string{"*"}
  11.  
  12. //注册入口路由组,并传入CORS处理器
  13. router := dispatcher.Router.GROUP("", CORSHandler(&corsConfig))
  14.  
  15. //在路由组里注册路由,会自动执行CORS处理器
  16. router.GET("/", func(ctx *httpdispatcher.Context) error {
  17. return nil
  18. })