ghttp.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. "net/http"
  10. "reflect"
  11. "time"
  12. "github.com/gorilla/websocket"
  13. "github.com/gogf/gf/v2/container/gmap"
  14. "github.com/gogf/gf/v2/container/gtype"
  15. "github.com/gogf/gf/v2/errors/gcode"
  16. "github.com/gogf/gf/v2/errors/gerror"
  17. "github.com/gogf/gf/v2/net/goai"
  18. "github.com/gogf/gf/v2/net/gsvc"
  19. "github.com/gogf/gf/v2/os/gcache"
  20. "github.com/gogf/gf/v2/os/gsession"
  21. )
  22. type (
  23. // Server wraps the http.Server and provides more rich features.
  24. Server struct {
  25. instance string // Instance name of current HTTP server.
  26. config ServerConfig // Server configuration.
  27. plugins []Plugin // Plugin array to extend server functionality.
  28. servers []*gracefulServer // Underlying http.Server array.
  29. serverCount *gtype.Int // Underlying http.Server number for internal usage.
  30. closeChan chan struct{} // Used for underlying server closing event notification.
  31. serveTree map[string]interface{} // The route maps tree.
  32. serveCache *gcache.Cache // Server caches for internal usage.
  33. routesMap map[string][]*HandlerItem // Route map mainly for route dumps and repeated route checks.
  34. statusHandlerMap map[string][]HandlerFunc // Custom status handler map.
  35. sessionManager *gsession.Manager // Session manager.
  36. openapi *goai.OpenApiV3 // The OpenApi specification management object.
  37. service gsvc.Service // The service for Registry.
  38. }
  39. // Router object.
  40. Router struct {
  41. Uri string // URI.
  42. Method string // HTTP method
  43. Domain string // Bound domain.
  44. RegRule string // Parsed regular expression for route matching.
  45. RegNames []string // Parsed router parameter names.
  46. Priority int // Just for reference.
  47. }
  48. // RouterItem is just for route dumps.
  49. RouterItem struct {
  50. Handler *HandlerItem // The handler.
  51. Server string // Server name.
  52. Address string // Listening address.
  53. Domain string // Bound domain.
  54. Type string // Router type.
  55. Middleware string // Bound middleware.
  56. Method string // Handler method name.
  57. Route string // Route URI.
  58. Priority int // Just for reference.
  59. IsServiceHandler bool // Is service handler.
  60. }
  61. // HandlerFunc is request handler function.
  62. HandlerFunc = func(r *Request)
  63. // handlerFuncInfo contains the HandlerFunc address and its reflection type.
  64. handlerFuncInfo struct {
  65. Func HandlerFunc // Handler function address.
  66. Type reflect.Type // Reflect type information for current handler, which is used for extensions of the handler feature.
  67. Value reflect.Value // Reflect value information for current handler, which is used for extensions of the handler feature.
  68. }
  69. // HandlerItem is the registered handler for route handling,
  70. // including middleware and hook functions.
  71. HandlerItem struct {
  72. Id int // Unique handler item id mark.
  73. Name string // Handler name, which is automatically retrieved from runtime stack when registered.
  74. Type string // Handler type: object/handler/middleware/hook.
  75. Info handlerFuncInfo // Handler function information.
  76. InitFunc HandlerFunc // Initialization function when request enters the object (only available for object register type).
  77. ShutFunc HandlerFunc // Shutdown function when request leaves out the object (only available for object register type).
  78. Middleware []HandlerFunc // Bound middleware array.
  79. HookName string // Hook type name, only available for the hook type.
  80. Router *Router // Router object.
  81. Source string // Registering source file `path:line`.
  82. }
  83. // HandlerItemParsed is the item parsed from URL.Path.
  84. HandlerItemParsed struct {
  85. Handler *HandlerItem // Handler information.
  86. Values map[string]string // Router values parsed from URL.Path.
  87. }
  88. // Listening file descriptor mapping.
  89. // The key is either "http" or "https" and the value is its FD.
  90. listenerFdMap = map[string]string
  91. // internalPanic is the custom panic for internal usage.
  92. internalPanic string
  93. )
  94. const (
  95. // FreePortAddress marks the server listens using random free port.
  96. FreePortAddress = ":0"
  97. )
  98. const (
  99. HeaderXUrlPath = "x-url-path" // Used for custom route handler, which does not change URL.Path.
  100. HookBeforeServe = "HOOK_BEFORE_SERVE" // Hook handler before route handler/file serving.
  101. HookAfterServe = "HOOK_AFTER_SERVE" // Hook handler after route handler/file serving.
  102. HookBeforeOutput = "HOOK_BEFORE_OUTPUT" // Hook handler before response output.
  103. HookAfterOutput = "HOOK_AFTER_OUTPUT" // Hook handler after response output.
  104. ServerStatusStopped = 0
  105. ServerStatusRunning = 1
  106. DefaultServerName = "default"
  107. DefaultDomainName = "default"
  108. HandlerTypeHandler = "handler"
  109. HandlerTypeObject = "object"
  110. HandlerTypeMiddleware = "middleware"
  111. HandlerTypeHook = "hook"
  112. )
  113. const (
  114. supportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
  115. defaultMethod = "ALL"
  116. routeCacheDuration = time.Hour
  117. ctxKeyForRequest = "gHttpRequestObject"
  118. contentTypeXml = "text/xml"
  119. contentTypeHtml = "text/html"
  120. contentTypeJson = "application/json"
  121. swaggerUIPackedPath = "/goframe/swaggerui"
  122. responseTraceIDHeader = "Trace-ID"
  123. specialMethodNameInit = "Init"
  124. specialMethodNameShut = "Shut"
  125. specialMethodNameIndex = "Index"
  126. gracefulShutdownTimeout = 5 * time.Second
  127. )
  128. const (
  129. exceptionExit internalPanic = "exit"
  130. exceptionExitAll internalPanic = "exit_all"
  131. exceptionExitHook internalPanic = "exit_hook"
  132. )
  133. var (
  134. // methodsMap stores all supported HTTP method.
  135. // It is used for quick HTTP method searching using map.
  136. methodsMap = make(map[string]struct{})
  137. // serverMapping stores more than one server instances for current processes.
  138. // The key is the name of the server, and the value is its instance.
  139. serverMapping = gmap.NewStrAnyMap(true)
  140. // serverRunning marks the running server counts.
  141. // If there is no successful server running or all servers' shutdown, this value is 0.
  142. serverRunning = gtype.NewInt()
  143. // wsUpGrader is the default up-grader configuration for websocket.
  144. wsUpGrader = websocket.Upgrader{
  145. // It does not check the origin in default, the application can do it itself.
  146. CheckOrigin: func(r *http.Request) bool {
  147. return true
  148. },
  149. }
  150. // allShutdownChan is the event for all servers have done its serving and exit.
  151. // It is used for process blocking purpose.
  152. allShutdownChan = make(chan struct{}, 1000)
  153. // serverProcessInitialized is used for lazy initialization for server.
  154. // The process can only be initialized once.
  155. serverProcessInitialized = gtype.NewBool()
  156. // gracefulEnabled is used for a graceful reload feature, which is false in default.
  157. gracefulEnabled = false
  158. // defaultValueTags are the struct tag names for default value storing.
  159. defaultValueTags = []string{"d", "default"}
  160. )
  161. var (
  162. ErrNeedJsonBody = gerror.NewOption(gerror.Option{
  163. Text: "the request body content should be JSON format",
  164. Code: gcode.CodeInvalidRequest,
  165. })
  166. )