ghttp.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package ghttp provides powerful http server and simple client implements.
  7. package ghttp
  8. import (
  9. "github.com/gogf/gf/container/gmap"
  10. "github.com/gogf/gf/container/gtype"
  11. "github.com/gogf/gf/os/gcache"
  12. "github.com/gogf/gf/os/gsession"
  13. "github.com/gorilla/websocket"
  14. "net/http"
  15. "reflect"
  16. "time"
  17. )
  18. type (
  19. // Server wraps the http.Server and provides more rich features.
  20. Server struct {
  21. name string // Unique name for instance management.
  22. config ServerConfig // Configuration.
  23. plugins []Plugin // Plugin array to extend server functionality.
  24. servers []*gracefulServer // Underlying http.Server array.
  25. serverCount *gtype.Int // Underlying http.Server count.
  26. closeChan chan struct{} // Used for underlying server closing event notification.
  27. serveTree map[string]interface{} // The route map tree.
  28. serveCache *gcache.Cache // Server caches for internal usage.
  29. routesMap map[string][]registeredRouteItem // Route map mainly for route dumps and repeated route checks.
  30. statusHandlerMap map[string][]HandlerFunc // Custom status handler map.
  31. sessionManager *gsession.Manager // Session manager.
  32. }
  33. // Router object.
  34. Router struct {
  35. Uri string // URI.
  36. Method string // HTTP method
  37. Domain string // Bound domain.
  38. RegRule string // Parsed regular expression for route matching.
  39. RegNames []string // Parsed router parameter names.
  40. Priority int // Just for reference.
  41. }
  42. // RouterItem is just for route dumps.
  43. RouterItem struct {
  44. Server string // Server name.
  45. Address string // Listening address.
  46. Domain string // Bound domain.
  47. Type int // Router type.
  48. Middleware string // Bound middleware.
  49. Method string // Handler method name.
  50. Route string // Route URI.
  51. Priority int // Just for reference.
  52. IsServiceHandler bool // Is service handler.
  53. handler *handlerItem // The handler.
  54. }
  55. // HandlerFunc is request handler function.
  56. HandlerFunc = func(r *Request)
  57. // handlerFuncInfo contains the HandlerFunc address and its reflect type.
  58. handlerFuncInfo struct {
  59. Func HandlerFunc // Handler function address.
  60. Type reflect.Type // Reflect type information for current handler, which is used for extension of handler feature.
  61. Value reflect.Value // Reflect value information for current handler, which is used for extension of handler feature.
  62. }
  63. // handlerItem is the registered handler for route handling,
  64. // including middleware and hook functions.
  65. handlerItem struct {
  66. Id int // Unique handler item id mark.
  67. Name string // Handler name, which is automatically retrieved from runtime stack when registered.
  68. Type int // Handler type: object/handler/controller/middleware/hook.
  69. Info handlerFuncInfo // Handler function information.
  70. InitFunc HandlerFunc // Initialization function when request enters the object (only available for object register type).
  71. ShutFunc HandlerFunc // Shutdown function when request leaves out the object (only available for object register type).
  72. Middleware []HandlerFunc // Bound middleware array.
  73. HookName string // Hook type name, only available for hook type.
  74. Router *Router // Router object.
  75. Source string // Registering source file `path:line`.
  76. }
  77. // handlerParsedItem is the item parsed from URL.Path.
  78. handlerParsedItem struct {
  79. Handler *handlerItem // Handler information.
  80. Values map[string]string // Router values parsed from URL.Path.
  81. }
  82. // registeredRouteItem stores the information of the router and is used for route map.
  83. registeredRouteItem struct {
  84. Source string // Source file path and its line number.
  85. Handler *handlerItem // Handler object.
  86. }
  87. // errorStack is the interface for Stack feature.
  88. errorStack interface {
  89. Error() string
  90. Stack() string
  91. }
  92. // Listening file descriptor mapping.
  93. // The key is either "http" or "https" and the value is its FD.
  94. listenerFdMap = map[string]string
  95. )
  96. const (
  97. HookBeforeServe = "HOOK_BEFORE_SERVE"
  98. HookAfterServe = "HOOK_AFTER_SERVE"
  99. HookBeforeOutput = "HOOK_BEFORE_OUTPUT"
  100. HookAfterOutput = "HOOK_AFTER_OUTPUT"
  101. ServerStatusStopped = 0
  102. ServerStatusRunning = 1
  103. supportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
  104. defaultServerName = "default"
  105. defaultDomainName = "default"
  106. defaultMethod = "ALL"
  107. handlerTypeHandler = 1
  108. handlerTypeObject = 2
  109. handlerTypeController = 3
  110. handlerTypeMiddleware = 4
  111. handlerTypeHook = 5
  112. exceptionExit = "exit"
  113. exceptionExitAll = "exit_all"
  114. exceptionExitHook = "exit_hook"
  115. routeCacheDuration = time.Hour
  116. methodNameInit = "Init"
  117. methodNameShut = "Shut"
  118. methodNameExit = "Exit"
  119. ctxKeyForRequest = "gHttpRequestObject"
  120. )
  121. var (
  122. // methodsMap stores all supported HTTP method,
  123. // it is used for quick HTTP method searching using map.
  124. methodsMap = make(map[string]struct{})
  125. // serverMapping stores more than one server instances for current process.
  126. // The key is the name of the server, and the value is its instance.
  127. serverMapping = gmap.NewStrAnyMap(true)
  128. // serverRunning marks the running server count.
  129. // If there is no successful server running or all servers' shutdown, this value is 0.
  130. serverRunning = gtype.NewInt()
  131. // wsUpGrader is the default up-grader configuration for websocket.
  132. wsUpGrader = websocket.Upgrader{
  133. // It does not check the origin in default, the application can do it itself.
  134. CheckOrigin: func(r *http.Request) bool {
  135. return true
  136. },
  137. }
  138. // allDoneChan is the event for all server have done its serving and exit.
  139. // It is used for process blocking purpose.
  140. allDoneChan = make(chan struct{}, 1000)
  141. // serverProcessInitialized is used for lazy initialization for server.
  142. // The process can only be initialized once.
  143. serverProcessInitialized = gtype.NewBool()
  144. // gracefulEnabled is used for graceful reload feature, which is false in default.
  145. gracefulEnabled = false
  146. // defaultValueTags is the struct tag names for default value storing.
  147. defaultValueTags = []string{"d", "default"}
  148. )