patrouter.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package router
  2. import (
  3. "net/http"
  4. "path"
  5. "strings"
  6. "zero/core/search"
  7. "zero/ngin/internal/context"
  8. )
  9. const (
  10. allowHeader = "Allow"
  11. allowMethodSeparator = ", "
  12. )
  13. type PatRouter struct {
  14. trees map[string]*search.Tree
  15. notFound http.Handler
  16. }
  17. func NewPatRouter() Router {
  18. return &PatRouter{
  19. trees: make(map[string]*search.Tree),
  20. }
  21. }
  22. func (pr *PatRouter) Handle(method, reqPath string, handler http.Handler) error {
  23. if !validMethod(method) {
  24. return ErrInvalidMethod
  25. }
  26. if len(reqPath) == 0 || reqPath[0] != '/' {
  27. return ErrInvalidPath
  28. }
  29. cleanPath := path.Clean(reqPath)
  30. if tree, ok := pr.trees[method]; ok {
  31. return tree.Add(cleanPath, handler)
  32. } else {
  33. tree = search.NewTree()
  34. pr.trees[method] = tree
  35. return tree.Add(cleanPath, handler)
  36. }
  37. }
  38. func (pr *PatRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  39. reqPath := path.Clean(r.URL.Path)
  40. if tree, ok := pr.trees[r.Method]; ok {
  41. if result, ok := tree.Search(reqPath); ok {
  42. if len(result.Params) > 0 {
  43. r = context.WithPathVars(r, result.Params)
  44. }
  45. result.Item.(http.Handler).ServeHTTP(w, r)
  46. return
  47. }
  48. }
  49. if allow, ok := pr.methodNotAllowed(r.Method, reqPath); ok {
  50. w.Header().Set(allowHeader, allow)
  51. w.WriteHeader(http.StatusMethodNotAllowed)
  52. } else {
  53. pr.handleNotFound(w, r)
  54. }
  55. }
  56. func (pr *PatRouter) SetNotFoundHandler(handler http.Handler) {
  57. pr.notFound = handler
  58. }
  59. func (pr *PatRouter) handleNotFound(w http.ResponseWriter, r *http.Request) {
  60. if pr.notFound != nil {
  61. pr.notFound.ServeHTTP(w, r)
  62. } else {
  63. http.NotFound(w, r)
  64. }
  65. }
  66. func (pr *PatRouter) methodNotAllowed(method, path string) (string, bool) {
  67. var allows []string
  68. for treeMethod, tree := range pr.trees {
  69. if treeMethod == method {
  70. continue
  71. }
  72. _, ok := tree.Search(path)
  73. if ok {
  74. allows = append(allows, treeMethod)
  75. }
  76. }
  77. if len(allows) > 0 {
  78. return strings.Join(allows, allowMethodSeparator), true
  79. } else {
  80. return "", false
  81. }
  82. }
  83. func validMethod(method string) bool {
  84. return method == http.MethodDelete || method == http.MethodGet ||
  85. method == http.MethodHead || method == http.MethodOptions ||
  86. method == http.MethodPatch || method == http.MethodPost ||
  87. method == http.MethodPut
  88. }