No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

166 líneas
5.7KB

  1. /* ----------------------------------------------------------------------
  2. * ______ ___ __
  3. * / ____/___ / | ____ __ ___ __/ /_ ___ ________
  4. * / / __/ __ \/ /| | / __ \/ / / / | /| / / __ \/ _ \/ ___/ _ \
  5. * / /_/ / /_/ / ___ |/ / / / /_/ /| |/ |/ / / / / __/ / / __/
  6. * \____/\____/_/ |_/_/ /_/\__. / |__/|__/_/ /_/\___/_/ \___/
  7. * /____/
  8. *
  9. * (C) Copyright 2015 GoAnywhere (http://goanywhere.io).
  10. * ----------------------------------------------------------------------
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. * ----------------------------------------------------------------------*/
  23. package rex
  24. import (
  25. "fmt"
  26. "net/http"
  27. "reflect"
  28. "runtime"
  29. "time"
  30. "github.com/gorilla/mux"
  31. )
  32. type Router struct {
  33. middleware *middleware
  34. mux *mux.Router
  35. ready bool
  36. subrouters []*Router
  37. }
  38. func New() *Router {
  39. return &Router{
  40. middleware: new(middleware),
  41. mux: mux.NewRouter().StrictSlash(true),
  42. }
  43. }
  44. // build constructs all router/subrouters along with their middleware modules chain.
  45. func (self *Router) build() http.Handler {
  46. if !self.ready {
  47. // * add router into middlware stack to serve as final http.Handler.
  48. self.Use(func(http.Handler) http.Handler {
  49. return self.mux
  50. })
  51. // * add subrouters into middlware stack to serve as final http.Handler.
  52. for index := 0; index < len(self.subrouters); index++ {
  53. router := self.subrouters[index]
  54. router.Use(func(http.Handler) http.Handler {
  55. return router.mux
  56. })
  57. }
  58. self.ready = true
  59. }
  60. return self.middleware
  61. }
  62. // register adds the http.Handler/http.HandleFunc into Gorilla mux.
  63. func (self *Router) register(method string, pattern string, handler interface{}) {
  64. // finds the full function name (with package) as its mappings.
  65. var name = runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
  66. switch H := handler.(type) {
  67. case http.Handler:
  68. self.mux.Handle(pattern, H).Methods(method).Name(name)
  69. case func(http.ResponseWriter, *http.Request):
  70. self.mux.HandleFunc(pattern, H).Methods(method).Name(name)
  71. default:
  72. Fatalf("Unsupported handler (%s) passed in.", name)
  73. }
  74. }
  75. // Get is a shortcut for mux.HandleFunc(pattern, handler).Methods("GET"),
  76. // it also fetch the full function name of the handler (with package) to name the route.
  77. func (self *Router) Get(pattern string, handler interface{}) {
  78. self.register("GET", pattern, handler)
  79. }
  80. // Head is a shortcut for mux.HandleFunc(pattern, handler).Methods("HEAD")
  81. // it also fetch the full function name of the handler (with package) to name the route.
  82. func (self *Router) Head(pattern string, handler interface{}) {
  83. self.register("HEAD", pattern, handler)
  84. }
  85. // Options is a shortcut for mux.HandleFunc(pattern, handler).Methods("OPTIONS")
  86. // it also fetch the full function name of the handler (with package) to name the route.
  87. // NOTE method OPTIONS is **NOT** cachable, beware of what you are going to do.
  88. func (self *Router) Options(pattern string, handler interface{}) {
  89. self.register("OPTIONS", pattern, handler)
  90. }
  91. // Post is a shortcut for mux.HandleFunc(pattern, handler).Methods("POST")
  92. // it also fetch the full function name of the handler (with package) to name the route.
  93. func (self *Router) Post(pattern string, handler interface{}) {
  94. self.register("POST", pattern, handler)
  95. }
  96. // Put is a shortcut for mux.HandleFunc(pattern, handler).Methods("PUT")
  97. // it also fetch the full function name of the handler (with package) to name the route.
  98. func (self *Router) Put(pattern string, handler interface{}) {
  99. self.register("PUT", pattern, handler)
  100. }
  101. // Delete is a shortcut for mux.HandleFunc(pattern, handler).Methods("DELETE")
  102. // it also fetch the full function name of the handler (with package) to name the route.
  103. func (self *Router) Delete(pattern string, handler interface{}) {
  104. self.register("Delete", pattern, handler)
  105. }
  106. // Group creates a new application group under the given path prefix.
  107. func (self *Router) Group(prefix string) *Router {
  108. var middleware = new(middleware)
  109. self.mux.PathPrefix(prefix).Handler(middleware)
  110. var mux = self.mux.PathPrefix(prefix).Subrouter()
  111. router := &Router{middleware: middleware, mux: mux}
  112. self.subrouters = append(self.subrouters, router)
  113. return router
  114. }
  115. // Name returns route name for the given request, if any.
  116. func (self *Router) Name(r *http.Request) (name string) {
  117. var match mux.RouteMatch
  118. if self.mux.Match(r, &match) {
  119. name = match.Route.GetName()
  120. }
  121. return name
  122. }
  123. // Use add the middleware module into the stack chain.
  124. func (self *Router) Use(module func(http.Handler) http.Handler) {
  125. self.middleware.stack = append(self.middleware.stack, module)
  126. }
  127. // ServeHTTP dispatches the request to the handler whose
  128. // pattern most closely matches the request URL.
  129. func (self *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  130. self.build().ServeHTTP(w, r)
  131. }
  132. // Run starts the application server to serve incoming requests at the given address.
  133. func (self *Router) Run() {
  134. runtime.GOMAXPROCS(config.maxprocs)
  135. go func() {
  136. time.Sleep(500 * time.Millisecond)
  137. Infof("Application server is listening at %d", config.port)
  138. }()
  139. if err := http.ListenAndServe(fmt.Sprintf(":%d", config.port), self); err != nil {
  140. Fatalf("Failed to start the server: %v", err)
  141. }
  142. }