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.

server.go 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. // Group creates a new application group under the given path prefix.
  80. func (self *server) Group(prefix string) *server {
  81. var middleware = new(middleware)
  82. self.mux.PathPrefix(prefix).Handler(middleware)
  83. var mux = self.mux.PathPrefix(prefix).Subrouter()
  84. server := &server{middleware: middleware, mux: mux}
  85. self.subservers = append(self.subservers, server)
  86. return server
  87. }
  88. // Name returns route name for the given request, if any.
  89. func (self *server) Name(r *http.Request) (name string) {
  90. var match mux.RouteMatch
  91. if self.mux.Match(r, &match) {
  92. name = match.Route.GetName()
  93. }
  94. return name
  95. }
  96. // FileServer registers a handler to serve HTTP (GET|HEAD) requests
  97. // with the contents of file system under the given directory.
  98. func (self *server) FileServer(prefix, dir string) {
  99. if abs, err := filepath.Abs(dir); err == nil {
  100. fs := http.StripPrefix(prefix, http.FileServer(http.Dir(abs)))
  101. self.mux.PathPrefix(prefix).Handler(fs)
  102. } else {
  103. log.Fatalf("Failed to setup file server: %v", err)
  104. }
  105. }
  106. // Use add the middleware module into the stack chain.
  107. func (self *server) Use(module func(http.Handler) http.Handler) {
  108. self.middleware.stack = append(self.middleware.stack, module)
  109. }
  110. // GET is a shortcut for mux.HandleFunc(pattern, handler).Methods("GET"),
  111. // it also fetch the full function name of the handler (with package) to name the route.
  112. func (self *server) GET(pattern string, handler interface{}) {
  113. self.register(pattern, handler, "GET")
  114. }
  115. // HEAD is a shortcut for mux.HandleFunc(pattern, handler).Methods("HEAD")
  116. // it also fetch the full function name of the handler (with package) to name the route.
  117. func (self *server) HEAD(pattern string, handler interface{}) {
  118. self.register(pattern, handler, "HEAD")
  119. }
  120. // OPTIONS is a shortcut for mux.HandleFunc(pattern, handler).Methods("OPTIONS")
  121. // it also fetch the full function name of the handler (with package) to name the route.
  122. // NOTE method OPTIONS is **NOT** cachable, beware of what you are going to do.
  123. func (self *server) OPTIONS(pattern string, handler interface{}) {
  124. self.register(pattern, handler, "OPTIONS")
  125. }
  126. // POST is a shortcut for mux.HandleFunc(pattern, handler).Methods("POST")
  127. // it also fetch the full function name of the handler (with package) to name the route.
  128. func (self *server) POST(pattern string, handler interface{}) {
  129. self.register(pattern, handler, "POST")
  130. }
  131. // PUT is a shortcut for mux.HandleFunc(pattern, handler).Methods("PUT")
  132. // it also fetch the full function name of the handler (with package) to name the route.
  133. func (self *server) PUT(pattern string, handler interface{}) {
  134. self.register(pattern, handler, "PUT")
  135. }
  136. // DELETE is a shortcut for mux.HandleFunc(pattern, handler).Methods("DELETE")
  137. // it also fetch the full function name of the handler (with package) to name the route.
  138. func (self *server) DELETE(pattern string, handler interface{}) {
  139. self.register(pattern, handler, "DELETE")
  140. }
  141. // TRACE is a shortcut for mux.HandleFunc(pattern, handler).Methods("TRACE")
  142. // it also fetch the full function name of the handler (with package) to name the route.
  143. func (self *server) TRACE(pattern string, handler interface{}) {
  144. self.register(pattern, handler, "TRACE")
  145. }
  146. // CONNECT is a shortcut for mux.HandleFunc(pattern, handler).Methods("CONNECT")
  147. // it also fetch the full function name of the handler (with package) to name the route.
  148. func (self *server) CONNECT(pattern string, handler interface{}) {
  149. self.register(pattern, handler, "CONNECT")
  150. }
  151. // ServeHTTP dispatches the request to the handler whose
  152. // pattern most closely matches the request URL.
  153. func (self *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  154. self.build().ServeHTTP(w, r)
  155. }
  156. // Run starts the application server to serve incoming requests at the given address.
  157. func (self *server) Run() {
  158. runtime.GOMAXPROCS(maxprocs)
  159. go func() {
  160. time.Sleep(500 * time.Millisecond)
  161. Infof("Application server is listening at %d", port)
  162. }()
  163. if err := http.ListenAndServe(fmt.Sprintf(":%d", port), self); err != nil {
  164. Fatalf("Failed to start the server: %v", err)
  165. }
  166. }
  167. // Vars returns the route variables for the current request, if any.
  168. func (self *server) Vars(r *http.Request) map[string]string {
  169. return mux.Vars(r)
  170. }