middlewares.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package core
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "strings"
  5. )
  6. func CorsMiddleWare() gin.HandlerFunc {
  7. return func(context *gin.Context) {
  8. method := context.Request.Method
  9. origin := context.Request.Header.Get("Origin") //请求头部
  10. if origin != "" {
  11. //接收客户端发送的origin (重要!)
  12. context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  13. //服务器支持的所有跨域请求的方法
  14. context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  15. //允许跨域设置可以返回其他子段,可以自定义字段
  16. context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
  17. // 允许浏览器(客户端)可以解析的头部 (重要)
  18. context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
  19. //设置缓存时间
  20. //c.Header("Access-Control-Max-Age", "172800")
  21. //允许客户端传递校验信息比如 cookie (重要)
  22. context.Header("Access-Control-Allow-Credentials", "true")
  23. }
  24. //允许类型校验
  25. if method == "OPTIONS" {
  26. context.AbortWithStatus(200)
  27. } else {
  28. context.Next()
  29. }
  30. }
  31. }
  32. func RouteReplace(router *gin.Engine, routeStr string) gin.HandlerFunc {
  33. return func(context *gin.Context) {
  34. // 去掉 前缀
  35. newPath := strings.TrimPrefix(context.Request.URL.Path, routeStr)
  36. if newPath == context.Request.URL.Path {
  37. // 如果没有匹配到前缀,直接放行
  38. context.Next()
  39. return
  40. }
  41. if newPath == "" {
  42. newPath = "/"
  43. }
  44. // 修改请求路径并重新处理
  45. context.Request.URL.Path = newPath
  46. router.HandleContext(context)
  47. context.Abort()
  48. }
  49. }