ghttp.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). 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 feature.
  20. Server struct {
  21. name string // Unique name for instance management.
  22. config ServerConfig // Configuration.
  23. plugins []Plugin // Plugin array.
  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 cache 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. // Router item 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. // handlerItem is the registered handler for route handling,
  56. // including middleware and hook functions.
  57. handlerItem struct {
  58. itemId int // Unique handler item id mark.
  59. itemName string // Handler name, which is automatically retrieved from runtime stack when registered.
  60. itemType int // Handler type: object/handler/controller/middleware/hook.
  61. itemFunc HandlerFunc // Handler address.
  62. initFunc HandlerFunc // Initialization function when request enters the object(only available for object register type).
  63. shutFunc HandlerFunc // Shutdown function when request leaves out the object(only available for object register type).
  64. middleware []HandlerFunc // Bound middleware array.
  65. ctrlInfo *handlerController // Controller information for reflect usage.
  66. hookName string // Hook type name.
  67. router *Router // Router object.
  68. source string // Source file path:line when registering.
  69. }
  70. // handlerParsedItem is the item parsed from URL.Path.
  71. handlerParsedItem struct {
  72. handler *handlerItem // Handler information.
  73. values map[string]string // Router values parsed from URL.Path.
  74. }
  75. // handlerController is the controller information used for reflect.
  76. handlerController struct {
  77. name string // Handler method name.
  78. reflect reflect.Type // Reflect type of the controller.
  79. }
  80. // registeredRouteItem stores the information of the router and is used for route map.
  81. registeredRouteItem struct {
  82. source string // Source file path and its line number.
  83. handler *handlerItem // Handler object.
  84. }
  85. // errorStack is the interface for Stack feature.
  86. errorStack interface {
  87. Error() string
  88. Stack() string
  89. }
  90. // Request handler function.
  91. HandlerFunc = func(r *Request)
  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. HOOK_BEFORE_SERVE = "HOOK_BEFORE_SERVE" // Deprecated, use HookBeforeServe instead.
  98. HOOK_AFTER_SERVE = "HOOK_AFTER_SERVE" // Deprecated, use HookAfterServe instead.
  99. HOOK_BEFORE_OUTPUT = "HOOK_BEFORE_OUTPUT" // Deprecated, use HookBeforeOutput instead.
  100. HOOK_AFTER_OUTPUT = "HOOK_AFTER_OUTPUT" // Deprecated, use HookAfterOutput instead.
  101. HookBeforeServe = "HOOK_BEFORE_SERVE"
  102. HookAfterServe = "HOOK_AFTER_SERVE"
  103. HookBeforeOutput = "HOOK_BEFORE_OUTPUT"
  104. HookAfterOutput = "HOOK_AFTER_OUTPUT"
  105. ServerStatusStopped = 0
  106. ServerStatusRunning = 1
  107. SupportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
  108. defaultServerName = "default"
  109. defaultDomainName = "default"
  110. defaultMethod = "ALL"
  111. handlerTypeHandler = 1
  112. handlerTypeObject = 2
  113. handlerTypeController = 3
  114. handlerTypeMiddleware = 4
  115. handlerTypeHook = 5
  116. exceptionExit = "exit"
  117. exceptionExitAll = "exit_all"
  118. exceptionExitHook = "exit_hook"
  119. routeCacheDuration = time.Hour
  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 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. )