github.com/gogf/gf/v2@v2.7.4/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/gogf/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/gogf/gf/v2/container/gmap"
    19  	"github.com/gogf/gf/v2/container/gtype"
    20  	"github.com/gogf/gf/v2/errors/gcode"
    21  	"github.com/gogf/gf/v2/errors/gerror"
    22  	"github.com/gogf/gf/v2/net/goai"
    23  	"github.com/gogf/gf/v2/net/gsvc"
    24  	"github.com/gogf/gf/v2/os/gcache"
    25  	"github.com/gogf/gf/v2/os/gctx"
    26  	"github.com/gogf/gf/v2/os/gsession"
    27  	"github.com/gogf/gf/v2/os/gstructs"
    28  	"github.com/gogf/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  	contentTypeJavascript                   = "application/javascript"
   158  	swaggerUIPackedPath                     = "/goframe/swaggerui"
   159  	responseHeaderTraceID                   = "Trace-ID"
   160  	responseHeaderContentLength             = "Content-Length"
   161  	specialMethodNameInit                   = "Init"
   162  	specialMethodNameShut                   = "Shut"
   163  	specialMethodNameIndex                  = "Index"
   164  	defaultEndpointPort                     = 80
   165  	noPrintInternalRoute                    = "internalMiddlewareServerTracing"
   166  )
   167  
   168  const (
   169  	exceptionExit     internalPanic = "exit"
   170  	exceptionExitAll  internalPanic = "exit_all"
   171  	exceptionExitHook internalPanic = "exit_hook"
   172  )
   173  
   174  var (
   175  	// methodsMap stores all supported HTTP method.
   176  	// It is used for quick HTTP method searching using map.
   177  	methodsMap = make(map[string]struct{})
   178  
   179  	// serverMapping stores more than one server instances for current processes.
   180  	// The key is the name of the server, and the value is its instance.
   181  	serverMapping = gmap.NewStrAnyMap(true)
   182  
   183  	// serverRunning marks the running server counts.
   184  	// If there is no successful server running or all servers' shutdown, this value is 0.
   185  	serverRunning = gtype.NewInt()
   186  
   187  	// wsUpGrader is the default up-grader configuration for websocket.
   188  	wsUpGrader = websocket.Upgrader{
   189  		// It does not check the origin in default, the application can do it itself.
   190  		CheckOrigin: func(r *http.Request) bool {
   191  			return true
   192  		},
   193  	}
   194  	// allShutdownChan is the event for all servers have done its serving and exit.
   195  	// It is used for process blocking purpose.
   196  	allShutdownChan = make(chan struct{}, 1000)
   197  
   198  	// serverProcessInitialized is used for lazy initialization for server.
   199  	// The process can only be initialized once.
   200  	serverProcessInitialized = gtype.NewBool()
   201  
   202  	// gracefulEnabled is used for a graceful reload feature, which is false in default.
   203  	gracefulEnabled = false
   204  
   205  	// defaultValueTags are the struct tag names for default value storing.
   206  	defaultValueTags = []string{gtag.DefaultShort, gtag.Default}
   207  )
   208  
   209  var (
   210  	ErrNeedJsonBody = gerror.NewWithOption(gerror.Option{
   211  		Text: "the request body content should be JSON format",
   212  		Code: gcode.CodeInvalidRequest,
   213  	})
   214  )