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