You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

router.go 4.7KB

9 jaren geleden
9 jaren geleden
9 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package rex
  2. import (
  3. "fmt"
  4. "net/http"
  5. "reflect"
  6. "runtime"
  7. "time"
  8. "github.com/gorilla/mux"
  9. )
  10. type Router struct {
  11. middleware *middleware
  12. mux *mux.Router
  13. ready bool
  14. subrouters []*Router
  15. }
  16. func New() *Router {
  17. return &Router{
  18. middleware: new(middleware),
  19. mux: mux.NewRouter().StrictSlash(true),
  20. }
  21. }
  22. // build constructs all router/subrouters along with their middleware modules chain.
  23. func (self *Router) build() http.Handler {
  24. if !self.ready {
  25. // * add router into middlware stack to serve as final http.Handler.
  26. self.Use(func(http.Handler) http.Handler {
  27. return self.mux
  28. })
  29. // * add subrouters into middlware stack to serve as final http.Handler.
  30. for index := 0; index < len(self.subrouters); index++ {
  31. router := self.subrouters[index]
  32. router.Use(func(http.Handler) http.Handler {
  33. return router.mux
  34. })
  35. }
  36. self.ready = true
  37. }
  38. return self.middleware
  39. }
  40. // register adds the http.Handler/http.HandleFunc into Gorilla mux.
  41. func (self *Router) register(method string, pattern string, handler interface{}) {
  42. // finds the full function name (with package) as its mappings.
  43. var name = runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
  44. switch H := handler.(type) {
  45. case http.Handler:
  46. self.mux.Handle(pattern, H).Methods(method).Name(name)
  47. case func(http.ResponseWriter, *http.Request):
  48. self.mux.HandleFunc(pattern, H).Methods(method).Name(name)
  49. default:
  50. Fatalf("Unsupported handler (%s) passed in.", name)
  51. }
  52. }
  53. // Get is a shortcut for mux.HandleFunc(pattern, handler).Methods("GET"),
  54. // it also fetch the full function name of the handler (with package) to name the route.
  55. func (self *Router) Get(pattern string, handler interface{}) {
  56. self.register("GET", pattern, handler)
  57. }
  58. // Head is a shortcut for mux.HandleFunc(pattern, handler).Methods("HEAD")
  59. // it also fetch the full function name of the handler (with package) to name the route.
  60. func (self *Router) Head(pattern string, handler interface{}) {
  61. self.register("HEAD", pattern, handler)
  62. }
  63. // Options is a shortcut for mux.HandleFunc(pattern, handler).Methods("OPTIONS")
  64. // it also fetch the full function name of the handler (with package) to name the route.
  65. // NOTE method OPTIONS is **NOT** cachable, beware of what you are going to do.
  66. func (self *Router) Options(pattern string, handler interface{}) {
  67. self.register("OPTIONS", pattern, handler)
  68. }
  69. // Post is a shortcut for mux.HandleFunc(pattern, handler).Methods("POST")
  70. // it also fetch the full function name of the handler (with package) to name the route.
  71. func (self *Router) Post(pattern string, handler interface{}) {
  72. self.register("POST", pattern, handler)
  73. }
  74. // Put is a shortcut for mux.HandleFunc(pattern, handler).Methods("PUT")
  75. // it also fetch the full function name of the handler (with package) to name the route.
  76. func (self *Router) Put(pattern string, handler interface{}) {
  77. self.register("PUT", pattern, handler)
  78. }
  79. // Delete is a shortcut for mux.HandleFunc(pattern, handler).Methods("DELETE")
  80. // it also fetch the full function name of the handler (with package) to name the route.
  81. func (self *Router) Delete(pattern string, handler interface{}) {
  82. self.register("Delete", pattern, handler)
  83. }
  84. // Group creates a new application group under the given path prefix.
  85. func (self *Router) Group(prefix string) *Router {
  86. var middleware = new(middleware)
  87. self.mux.PathPrefix(prefix).Handler(middleware)
  88. var mux = self.mux.PathPrefix(prefix).Subrouter()
  89. router := &Router{middleware: middleware, mux: mux}
  90. self.subrouters = append(self.subrouters, router)
  91. return router
  92. }
  93. // Name returns route name for the given request, if any.
  94. func (self *Router) Name(r *http.Request) (name string) {
  95. var match mux.RouteMatch
  96. if self.mux.Match(r, &match) {
  97. name = match.Route.GetName()
  98. }
  99. return name
  100. }
  101. // Use add the middleware module into the stack chain.
  102. func (self *Router) Use(module func(http.Handler) http.Handler) {
  103. self.middleware.stack = append(self.middleware.stack, module)
  104. }
  105. // ServeHTTP dispatches the request to the handler whose
  106. // pattern most closely matches the request URL.
  107. func (self *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  108. self.build().ServeHTTP(w, r)
  109. }
  110. // Run starts the application server to serve incoming requests at the given address.
  111. func (self *Router) Run() {
  112. runtime.GOMAXPROCS(config.maxprocs)
  113. go func() {
  114. time.Sleep(500 * time.Millisecond)
  115. Infof("Application server is listening at %d", config.port)
  116. }()
  117. if err := http.ListenAndServe(fmt.Sprintf(":%d", config.port), self); err != nil {
  118. Fatalf("Failed to start the server: %v", err)
  119. }
  120. }
  121. // Vars returns the route variables for the current request, if any.
  122. func (self *Router) Vars(r *http.Request) map[string]string {
  123. return mux.Vars(r)
  124. }