Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

server.go 5.9KB

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