選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

166 行
5.6KB

  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. module *module
  34. mux *mux.Router
  35. ready bool
  36. subrouters []*Router
  37. }
  38. func New() *Router {
  39. return &Router{
  40. module: new(module),
  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. self.ready = true
  48. // * activate router's middleware modules.
  49. self.module.Use(func(http.Handler) http.Handler {
  50. return self.mux
  51. })
  52. // * activate subrouters's middleware modules.
  53. for index := 0; index < len(self.subrouters); index++ {
  54. sr := self.subrouters[index]
  55. sr.module.Use(func(http.Handler) http.Handler {
  56. return sr.mux
  57. })
  58. }
  59. }
  60. return self.module
  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 module = new(module)
  109. self.mux.PathPrefix(prefix).Handler(module)
  110. var mux = self.mux.PathPrefix(prefix).Subrouter()
  111. router := &Router{module: module, 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.module.Use(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. }