Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

190 lines
5.9KB

  1. package rex
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "path/filepath"
  8. "reflect"
  9. "runtime"
  10. "sync"
  11. "time"
  12. "github.com/goanywhere/env"
  13. "github.com/gorilla/mux"
  14. )
  15. var (
  16. debug bool
  17. port int
  18. maxprocs int
  19. once sync.Once
  20. )
  21. type Server struct {
  22. middleware *middleware
  23. mux *mux.Router
  24. ready bool
  25. subservers []*Server
  26. }
  27. func New() *Server {
  28. self := &Server{
  29. middleware: new(middleware),
  30. mux: mux.NewRouter().StrictSlash(true),
  31. }
  32. self.configure()
  33. return self
  34. }
  35. func (self *Server) configure() {
  36. once.Do(func() {
  37. flag.BoolVar(&debug, "debug", env.Bool("DEBUG", true), "flag to toggle debug mode")
  38. flag.IntVar(&port, "port", env.Int("PORT", 5000), "port to run the application server")
  39. flag.IntVar(&maxprocs, "maxprocs", env.Int("MAXPROCS", runtime.NumCPU()), "maximum cpu processes to run the server")
  40. flag.Parse()
  41. })
  42. }
  43. // build constructs all server/subservers along with their middleware modules chain.
  44. func (self *Server) build() http.Handler {
  45. if !self.ready {
  46. // * add server mux into middlware stack to serve as final http.Handler.
  47. self.Use(func(http.Handler) http.Handler {
  48. return self.mux
  49. })
  50. // * add subservers into middlware stack to serve as final http.Handler.
  51. for index := 0; index < len(self.subservers); index++ {
  52. server := self.subservers[index]
  53. server.Use(func(http.Handler) http.Handler {
  54. return server.mux
  55. })
  56. }
  57. self.ready = true
  58. }
  59. return self.middleware
  60. }
  61. // register adds the http.Handler/http.HandleFunc into Gorilla mux.
  62. func (self *Server) register(pattern string, handler interface{}, methods ...string) {
  63. // finds the full function name (with package) as its mappings.
  64. var name = runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
  65. switch H := handler.(type) {
  66. case http.Handler:
  67. self.mux.Handle(pattern, H).Methods(methods...).Name(name)
  68. case func(http.ResponseWriter, *http.Request):
  69. self.mux.HandleFunc(pattern, H).Methods(methods...).Name(name)
  70. default:
  71. Fatalf("Unsupported handler (%s) passed in.", name)
  72. }
  73. }
  74. // Any maps most common HTTP methods request to the given `http.Handler`.
  75. // Supports: GET | POST | PUT | DELETE | OPTIONS | HEAD
  76. func (self *Server) Any(pattern string, handler interface{}) {
  77. self.register(pattern, handler, "GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
  78. }
  79. // Get is a shortcut for mux.HandleFunc(pattern, handler).Methods("GET"),
  80. // it also fetch the full function name of the handler (with package) to name the route.
  81. func (self *Server) Get(pattern string, handler interface{}) {
  82. self.register(pattern, handler, "GET")
  83. }
  84. // Head is a shortcut for mux.HandleFunc(pattern, handler).Methods("HEAD")
  85. // it also fetch the full function name of the handler (with package) to name the route.
  86. func (self *Server) Head(pattern string, handler interface{}) {
  87. self.register(pattern, handler, "HEAD")
  88. }
  89. // Options is a shortcut for mux.HandleFunc(pattern, handler).Methods("OPTIONS")
  90. // it also fetch the full function name of the handler (with package) to name the route.
  91. // NOTE method OPTIONS is **NOT** cachable, beware of what you are going to do.
  92. func (self *Server) Options(pattern string, handler interface{}) {
  93. self.register(pattern, handler, "OPTIONS")
  94. }
  95. // Post is a shortcut for mux.HandleFunc(pattern, handler).Methods("POST")
  96. // it also fetch the full function name of the handler (with package) to name the route.
  97. func (self *Server) Post(pattern string, handler interface{}) {
  98. self.register(pattern, handler, "POST")
  99. }
  100. // Put is a shortcut for mux.HandleFunc(pattern, handler).Methods("PUT")
  101. // it also fetch the full function name of the handler (with package) to name the route.
  102. func (self *Server) Put(pattern string, handler interface{}) {
  103. self.register(pattern, handler, "PUT")
  104. }
  105. // Delete is a shortcut for mux.HandleFunc(pattern, handler).Methods("DELETE")
  106. // it also fetch the full function name of the handler (with package) to name the route.
  107. func (self *Server) Delete(pattern string, handler interface{}) {
  108. self.register(pattern, handler, "DELETE")
  109. }
  110. // Group creates a new application group under the given path prefix.
  111. func (self *Server) Group(prefix string) *Server {
  112. var middleware = new(middleware)
  113. self.mux.PathPrefix(prefix).Handler(middleware)
  114. var mux = self.mux.PathPrefix(prefix).Subrouter()
  115. server := &Server{middleware: middleware, mux: mux}
  116. self.subservers = append(self.subservers, server)
  117. return server
  118. }
  119. // Name returns route name for the given request, if any.
  120. func (self *Server) Name(r *http.Request) (name string) {
  121. var match mux.RouteMatch
  122. if self.mux.Match(r, &match) {
  123. name = match.Route.GetName()
  124. }
  125. return name
  126. }
  127. // FileServer registers a handler to serve HTTP (GET|HEAD) requests
  128. // with the contents of file system under the given directory.
  129. func (self *Server) FileServer(prefix, dir string) {
  130. if abs, err := filepath.Abs(dir); err == nil {
  131. fs := http.StripPrefix(prefix, http.FileServer(http.Dir(abs)))
  132. self.mux.PathPrefix(prefix).Handler(fs)
  133. } else {
  134. log.Fatalf("Failed to setup file server: %v", err)
  135. }
  136. }
  137. // Use add the middleware module into the stack chain.
  138. func (self *Server) Use(module func(http.Handler) http.Handler) {
  139. self.middleware.stack = append(self.middleware.stack, module)
  140. }
  141. // ServeHTTP dispatches the request to the handler whose
  142. // pattern most closely matches the request URL.
  143. func (self *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  144. self.build().ServeHTTP(w, r)
  145. }
  146. // Run starts the application server to serve incoming requests at the given address.
  147. func (self *Server) Run() {
  148. runtime.GOMAXPROCS(maxprocs)
  149. go func() {
  150. time.Sleep(500 * time.Millisecond)
  151. Infof("Application server is listening at %d", port)
  152. }()
  153. if err := http.ListenAndServe(fmt.Sprintf(":%d", port), self); err != nil {
  154. Fatalf("Failed to start the server: %v", err)
  155. }
  156. }
  157. // Vars returns the route variables for the current request, if any.
  158. func (self *Server) Vars(r *http.Request) map[string]string {
  159. return mux.Vars(r)
  160. }