Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

149 lines
4.7KB

  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. }