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.

189 lines
6.3KB

  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 middleware struct {
  33. cache http.Handler
  34. stack []func(http.Handler) http.Handler
  35. }
  36. // build sets up the whole middleware modules in a FIFO chain.
  37. func (self *middleware) build() http.Handler {
  38. if self.cache == nil {
  39. var next http.Handler = http.DefaultServeMux
  40. // Activate modules in FIFO order.
  41. for index := len(self.stack) - 1; index >= 0; index-- {
  42. next = self.stack[index](next)
  43. }
  44. self.cache = next
  45. }
  46. return self.cache
  47. }
  48. // Implements the net/http Handler interface and calls the middleware stack.
  49. func (self *middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  50. self.build().ServeHTTP(w, r)
  51. }
  52. type Router struct {
  53. middleware *middleware
  54. mux *mux.Router
  55. ready bool
  56. subrouters []*Router
  57. }
  58. func New() *Router {
  59. return &Router{
  60. middleware: new(middleware),
  61. mux: mux.NewRouter().StrictSlash(true),
  62. }
  63. }
  64. // build constructs all router/subrouters along with their middleware modules chain.
  65. func (self *Router) build() http.Handler {
  66. if !self.ready {
  67. self.ready = true
  68. // * activate router's middleware modules.
  69. self.Use(func(http.Handler) http.Handler {
  70. return self.mux
  71. })
  72. // * activate subrouters's middleware modules.
  73. for index := 0; index < len(self.subrouters); index++ {
  74. sr := self.subrouters[index]
  75. sr.Use(func(http.Handler) http.Handler {
  76. return sr.mux
  77. })
  78. }
  79. }
  80. return self.middleware
  81. }
  82. // register adds the http.Handler/http.HandleFunc into Gorilla mux.
  83. func (self *Router) register(method string, pattern string, handler interface{}) {
  84. // finds the full function name (with package) as its mappings.
  85. var name = runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
  86. switch H := handler.(type) {
  87. case http.Handler:
  88. self.mux.Handle(pattern, H).Methods(method).Name(name)
  89. case func(http.ResponseWriter, *http.Request):
  90. self.mux.HandleFunc(pattern, H).Methods(method).Name(name)
  91. default:
  92. Fatalf("Unsupported handler (%s) passed in.", name)
  93. }
  94. }
  95. // Get is a shortcut for mux.HandleFunc(pattern, handler).Methods("GET"),
  96. // it also fetch the full function name of the handler (with package) to name the route.
  97. func (self *Router) Get(pattern string, handler interface{}) {
  98. self.register("GET", pattern, handler)
  99. }
  100. // Head is a shortcut for mux.HandleFunc(pattern, handler).Methods("HEAD")
  101. // it also fetch the full function name of the handler (with package) to name the route.
  102. func (self *Router) Head(pattern string, handler interface{}) {
  103. self.register("HEAD", pattern, handler)
  104. }
  105. // Options is a shortcut for mux.HandleFunc(pattern, handler).Methods("OPTIONS")
  106. // it also fetch the full function name of the handler (with package) to name the route.
  107. // NOTE method OPTIONS is **NOT** cachable, beware of what you are going to do.
  108. func (self *Router) Options(pattern string, handler interface{}) {
  109. self.register("OPTIONS", pattern, handler)
  110. }
  111. // Post is a shortcut for mux.HandleFunc(pattern, handler).Methods("POST")
  112. // it also fetch the full function name of the handler (with package) to name the route.
  113. func (self *Router) Post(pattern string, handler interface{}) {
  114. self.register("POST", pattern, handler)
  115. }
  116. // Put is a shortcut for mux.HandleFunc(pattern, handler).Methods("PUT")
  117. // it also fetch the full function name of the handler (with package) to name the route.
  118. func (self *Router) Put(pattern string, handler interface{}) {
  119. self.register("PUT", pattern, handler)
  120. }
  121. // Delete is a shortcut for mux.HandleFunc(pattern, handler).Methods("DELETE")
  122. // it also fetch the full function name of the handler (with package) to name the route.
  123. func (self *Router) Delete(pattern string, handler interface{}) {
  124. self.register("Delete", pattern, handler)
  125. }
  126. // Group creates a new application group under the given path prefix.
  127. func (self *Router) Group(prefix string) *Router {
  128. var middleware = new(middleware)
  129. self.mux.PathPrefix(prefix).Handler(middleware)
  130. var mux = self.mux.PathPrefix(prefix).Subrouter()
  131. router := &Router{middleware: middleware, mux: mux}
  132. self.subrouters = append(self.subrouters, router)
  133. return router
  134. }
  135. // Name returns route name for the given request, if any.
  136. func (self *Router) Name(r *http.Request) (name string) {
  137. var match mux.RouteMatch
  138. if self.mux.Match(r, &match) {
  139. name = match.Route.GetName()
  140. }
  141. return name
  142. }
  143. // Use add the middleware module into the stack chain.
  144. func (self *Router) Use(module func(http.Handler) http.Handler) {
  145. self.middleware.stack = append(self.middleware.stack, module)
  146. }
  147. // ServeHTTP dispatches the request to the handler whose
  148. // pattern most closely matches the request URL.
  149. func (self *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  150. self.build().ServeHTTP(w, r)
  151. }
  152. // Run starts the application server to serve incoming requests at the given address.
  153. func (self *Router) Run() {
  154. runtime.GOMAXPROCS(config.maxprocs)
  155. go func() {
  156. time.Sleep(500 * time.Millisecond)
  157. Infof("Application server is listening at %d", config.port)
  158. }()
  159. if err := http.ListenAndServe(fmt.Sprintf(":%d", config.port), self); err != nil {
  160. Fatalf("Failed to start the server: %v", err)
  161. }
  162. }