另客网go项目公用的代码库

router.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package linker
  2. import (
  3. "hash/crc32"
  4. "strconv"
  5. )
  6. type (
  7. Router struct {
  8. prefix string
  9. handlerContainer map[uint32]Handler
  10. routerMiddleware map[uint32][]Middleware
  11. middleware []Middleware
  12. }
  13. LinkRouter func(*Router)
  14. )
  15. func NewRouter() *Router {
  16. return &Router{
  17. handlerContainer: make(map[uint32]Handler),
  18. routerMiddleware: make(map[uint32][]Middleware),
  19. }
  20. }
  21. // 获取带命名空间router
  22. func (r *Router) NSRouter(prefix string, params ...LinkRouter) *Router {
  23. r.prefix = prefix
  24. for _, p := range params {
  25. p(r)
  26. }
  27. return r
  28. }
  29. // 命名空间路由注册路由和中间件
  30. func (r *Router) NSRoute(pattern string, handler Handler, middleware ...Middleware) LinkRouter {
  31. return func(r *Router) {
  32. if r.prefix != "" {
  33. pattern = r.prefix + pattern
  34. }
  35. r.Route(pattern, handler, middleware...)
  36. }
  37. }
  38. // 注册路由,路由中间件
  39. func (r *Router) Route(pattern string, handler Handler, middleware ...Middleware) *Router {
  40. operator := crc32.ChecksumIEEE([]byte(pattern))
  41. if operator <= OPERATOR_MAX {
  42. panic("Unavailable operator, the value of crc32 need less than " + strconv.Itoa(OPERATOR_MAX))
  43. }
  44. r.routerMiddleware[operator] = append(r.routerMiddleware[operator], middleware...)
  45. if _, ok := r.handlerContainer[operator]; !ok {
  46. r.handlerContainer[operator] = handler
  47. }
  48. return r
  49. }
  50. // 添加请求需要进行处理的中间件
  51. func (r *Router) Use(middleware ...Middleware) *Router {
  52. r.middleware = append(r.middleware, middleware...)
  53. return r
  54. }