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 6.9KB

9 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package rex
  2. import (
  3. "flag"
  4. "fmt"
  5. "net/http"
  6. "path/filepath"
  7. "runtime"
  8. "strings"
  9. "sync"
  10. "time"
  11. log "github.com/Sirupsen/logrus"
  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. var name = strings.Join(methods, "|") + ":" + pattern
  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(methods...).Name(name)
  69. case func(http.ResponseWriter, *http.Request):
  70. self.mux.HandleFunc(pattern, H).Methods(methods...).Name(name)
  71. default:
  72. panic("Unsupported handler: " + name)
  73. }
  74. }
  75. // Any maps most common HTTP methods request to the given `http.Handler`.
  76. // Supports: GET | POST | PUT | DELETE | OPTIONS | HEAD
  77. func (self *server) Any(pattern string, handler interface{}) {
  78. self.register(pattern, handler, "GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
  79. }
  80. // Group creates a new application group under the given path prefix.
  81. func (self *server) Group(prefix string) *server {
  82. var middleware = new(middleware)
  83. self.mux.PathPrefix(prefix).Handler(middleware)
  84. var mux = self.mux.PathPrefix(prefix).Subrouter()
  85. server := &server{middleware: middleware, mux: mux}
  86. self.subservers = append(self.subservers, server)
  87. return server
  88. }
  89. // Host creates a new application group under the given (sub)domain.
  90. func (self *server) Host(domain string) *server {
  91. var middleware = new(middleware)
  92. self.mux.Host(domain).Handler(middleware)
  93. var mux = self.mux.Host(domain).Subrouter()
  94. server := &server{middleware: middleware, mux: mux}
  95. self.subservers = append(self.subservers, server)
  96. return server
  97. }
  98. // Name returns route name for the given request, if any.
  99. func (self *server) Name(r *http.Request) (name string) {
  100. var match mux.RouteMatch
  101. if self.mux.Match(r, &match) {
  102. name = match.Route.GetName()
  103. }
  104. return name
  105. }
  106. // FileServer registers a handler to serve HTTP (GET|HEAD) requests
  107. // with the contents of file system under the given directory.
  108. func (self *server) FileServer(prefix, dir string) {
  109. if abs, err := filepath.Abs(dir); err == nil {
  110. fs := http.StripPrefix(prefix, http.FileServer(http.Dir(abs)))
  111. self.mux.PathPrefix(prefix).Handler(fs)
  112. } else {
  113. panic("Failed to setup file server: " + err.Error())
  114. }
  115. }
  116. // Use add the middleware module into the stack chain.
  117. func (self *server) Use(modules ...func(http.Handler) http.Handler) {
  118. self.middleware.stack = append(self.middleware.stack, modules...)
  119. }
  120. // Get is a shortcut for mux.HandleFunc(pattern, handler).Methods("GET"),
  121. // it also fetch the full function name of the handler (with package) to name the route.
  122. func (self *server) Get(pattern string, handler interface{}) {
  123. self.register(pattern, handler, "GET")
  124. }
  125. // Head is a shortcut for mux.HandleFunc(pattern, handler).Methods("HEAD")
  126. // it also fetch the full function name of the handler (with package) to name the route.
  127. func (self *server) Head(pattern string, handler interface{}) {
  128. self.register(pattern, handler, "HEAD")
  129. }
  130. // Options is a shortcut for mux.HandleFunc(pattern, handler).Methods("OPTIONS")
  131. // it also fetch the full function name of the handler (with package) to name the route.
  132. // NOTE method OPTIONS is **NOT** cachable, beware of what you are going to do.
  133. func (self *server) Options(pattern string, handler interface{}) {
  134. self.register(pattern, handler, "OPTIONS")
  135. }
  136. // POST is a shortcut for mux.HandleFunc(pattern, handler).Methods("POST")
  137. // it also fetch the full function name of the handler (with package) to name the route.
  138. func (self *server) Post(pattern string, handler interface{}) {
  139. self.register(pattern, handler, "POST")
  140. }
  141. // Put is a shortcut for mux.HandleFunc(pattern, handler).Methods("PUT")
  142. // it also fetch the full function name of the handler (with package) to name the route.
  143. func (self *server) Put(pattern string, handler interface{}) {
  144. self.register(pattern, handler, "PUT")
  145. }
  146. // Delete is a shortcut for mux.HandleFunc(pattern, handler).Methods("DELETE")
  147. // it also fetch the full function name of the handler (with package) to name the route.
  148. func (self *server) Delete(pattern string, handler interface{}) {
  149. self.register(pattern, handler, "DELETE")
  150. }
  151. // Trace is a shortcut for mux.HandleFunc(pattern, handler).Methods("TRACE")
  152. // it also fetch the full function name of the handler (with package) to name the route.
  153. func (self *server) Trace(pattern string, handler interface{}) {
  154. self.register(pattern, handler, "TRACE")
  155. }
  156. // Connect is a shortcut for mux.HandleFunc(pattern, handler).Methods("CONNECT")
  157. // it also fetch the full function name of the handler (with package) to name the route.
  158. func (self *server) Connect(pattern string, handler interface{}) {
  159. self.register(pattern, handler, "CONNECT")
  160. }
  161. // ServeHTTP dispatches the request to the handler whose
  162. // pattern most closely matches the request URL.
  163. func (self *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  164. self.build().ServeHTTP(w, r)
  165. }
  166. // Run starts the application server to serve incoming requests at the given address.
  167. func (self *server) Run() {
  168. runtime.GOMAXPROCS(maxprocs)
  169. go func() {
  170. time.Sleep(500 * time.Millisecond)
  171. log.Infof("Application server is listening at %d", port)
  172. }()
  173. if err := http.ListenAndServe(fmt.Sprintf(":%d", port), self); err != nil {
  174. log.Fatalf("Failed to start the server: %v", err)
  175. }
  176. }
  177. // Vars returns the route variables for the current request, if any.
  178. func (self *server) Vars(r *http.Request) map[string]string {
  179. return mux.Vars(r)
  180. }