middleware.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. "strings"
  6. )
  7. // EmptyMiddleware 不执行业务处理的中间件
  8. func EmptyMiddleware(r *ghttp.Request) {
  9. r.Middleware.Next()
  10. }
  11. type SkipperFunc func(request *ghttp.Request) bool
  12. // AllowPathPrefixSkipper 检查请求路径是否包含指定的前缀,如果包含则跳过
  13. func AllowPathPrefixSkipper(prefixes ...string) SkipperFunc {
  14. return func(request *ghttp.Request) bool {
  15. path := request.URL.Path
  16. pathLen := len(path)
  17. for _, p := range prefixes {
  18. if pl := len(p); pathLen >= pl && path[:pl] == p {
  19. return true
  20. }
  21. }
  22. return false
  23. }
  24. }
  25. // AllowMethodAndPathPrefixSkipper 检查请求方法和路径是否包含指定的前缀,如果不包含则跳过
  26. func AllowMethodAndPathPrefixSkipper(prefixes ...string) SkipperFunc {
  27. return func(request *ghttp.Request) bool {
  28. path := JoinRouter(request.Method, request.URL.Path)
  29. pathLen := len(path)
  30. for _, p := range prefixes {
  31. if pl := len(p); pathLen >= pl && path[:pl] == p {
  32. return true
  33. }
  34. }
  35. return false
  36. }
  37. }
  38. // JoinRouter 拼接路由
  39. func JoinRouter(method, path string) string {
  40. if len(path) > 0 && path[0] != '/' {
  41. path = "/" + path
  42. }
  43. return fmt.Sprintf("%s%s", strings.ToUpper(method), path)
  44. }
  45. // AllowPathPrefixNoSkipper 检查请求路径是否包含指定的前缀,如果包含则不跳过
  46. func AllowPathPrefixNoSkipper(prefixes ...string) SkipperFunc {
  47. return func(request *ghttp.Request) bool {
  48. path := request.URL.Path
  49. pathLen := len(path)
  50. for _, p := range prefixes {
  51. if pl := len(p); pathLen >= pl && path[:pl] == p {
  52. return false
  53. }
  54. }
  55. return true
  56. }
  57. }
  58. // SkipHandler 统一处理跳过函数
  59. func SkipHandler(r *ghttp.Request, skippers ...SkipperFunc) bool {
  60. for _, skipper := range skippers {
  61. if skipper(r) {
  62. return true
  63. }
  64. }
  65. return false
  66. }