Files
gf/net/ghttp/ghttp.go
hailaz ee24da4e72 refactor: interface{} to any and reflect.Ptr to reflect.Pointer (#4395)
This pull request standardizes the use of the Go 1.18+ `any` type alias
instead of `interface{}` throughout the codebase. The change improves
code readability and aligns with modern Go best practices. The update
touches many files, including core data structures, code generation
templates, logging utilities, and test data, ensuring consistency across
all usages.

**Type alias migration to `any`:**

* Replaced all instances of `interface{}` with `any` in core data
structures such as `garray` and in generated model structs (e.g.,
`TableUser`, `User1`, `User2`) to modernize type usage.
[[1]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L31-R31)
[[2]](diffhunk://#diff-6c19859cb32c7516ea95ddc8f8235460818eb2f24d2204308e0d9e1b19e7d90fL15-R19)
[[3]](diffhunk://#diff-a15ba2f5e830b4833c47b902515a4f9e5a4f83a3707698f3229b307ec3776b41L15-R18)
[[4]](diffhunk://#diff-52e0837e84d49221d1b810d88fdf78221f36cffcd664fb42f8aba49a79b974dcL15-R19)
[[5]](diffhunk://#diff-11c3457d1a23a4ca6ecd00d6b856289774936b6a708384cf03aff164044e7546L15-R19)
[[6]](diffhunk://#diff-2cff9cf8e6a0cc34087326d8c8149c3bbaf74c76fdbdf5a73daed13cc04249e1L15-R19)
* Updated function signatures, method parameters, and return types from
`interface{}` to `any` in various parts of the codebase, including code
generation, service logic, and logging utilities (e.g., `mlog`).
[[1]](diffhunk://#diff-175edfeea54490b8fe4e18ffcbea5835efaf8f0b8acf623359073987cae7eb76L48-R55)
[[2]](diffhunk://#diff-2b1953fb78cf3593d8c2c7d911e95b65fd0b847c30ed0b4d167d16fe6d781235L54-R74)
[[3]](diffhunk://#diff-e001b7a4b63603b9b14f00de78a4d570bb76c5f57d856a24643f071032e12356L66-R73)
[[4]](diffhunk://#diff-5582954e8a9983988dc8854ad82067fb2ac6269b988e07357ad8db1dfec5f1a0L39-R41)
[[5]](diffhunk://#diff-c5d51d56f487779a2b6207c7ad26c7a20bbadcc846ce094fe60ab4cabff58c51L107-R107)
[[6]](diffhunk://#diff-f96e6a9fdb416eb1804ceaba1fe0ac637bff22c43837f8bb849c2366ce72d4a1L116-R121)
[[7]](diffhunk://#diff-f94c83a1b08ae060d9346f4a6031fc4a7b9a0b894e02d9afaa09018b6598eac0L112-R112)
[[8]](diffhunk://#diff-748b11dbe8828dd4c040ec23cae0b8fe57ecf0a2d1b7694ea39102294e633c64L36-R36)
[[9]](diffhunk://#diff-748b11dbe8828dd4c040ec23cae0b8fe57ecf0a2d1b7694ea39102294e633c64L74-R74)
[[10]](diffhunk://#diff-748b11dbe8828dd4c040ec23cae0b8fe57ecf0a2d1b7694ea39102294e633c64L96-R96)

**Generated code and templates:**

* Adjusted generated files and code generation templates to output `any`
instead of `interface{}` for relevant struct fields and function
signatures, ensuring that new code generation aligns with the updated
convention.
[[1]](diffhunk://#diff-6c19859cb32c7516ea95ddc8f8235460818eb2f24d2204308e0d9e1b19e7d90fL15-R19)
[[2]](diffhunk://#diff-a15ba2f5e830b4833c47b902515a4f9e5a4f83a3707698f3229b307ec3776b41L15-R18)
[[3]](diffhunk://#diff-52e0837e84d49221d1b810d88fdf78221f36cffcd664fb42f8aba49a79b974dcL15-R19)
[[4]](diffhunk://#diff-11c3457d1a23a4ca6ecd00d6b856289774936b6a708384cf03aff164044e7546L15-R19)
[[5]](diffhunk://#diff-2cff9cf8e6a0cc34087326d8c8149c3bbaf74c76fdbdf5a73daed13cc04249e1L15-R19)
[[6]](diffhunk://#diff-175edfeea54490b8fe4e18ffcbea5835efaf8f0b8acf623359073987cae7eb76L48-R55)
[[7]](diffhunk://#diff-e001b7a4b63603b9b14f00de78a4d570bb76c5f57d856a24643f071032e12356L66-R73)
[[8]](diffhunk://#diff-5582954e8a9983988dc8854ad82067fb2ac6269b988e07357ad8db1dfec5f1a0L39-R41)

**Container and utility updates:**

* Refactored the `garray` container implementation and related
constructors/methods to use `[]any` instead of `[]interface{}`, along
with corresponding function signatures.
[[1]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L31-R31)
[[2]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L52-R52)
[[3]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L62-R62)
[[4]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L73-R86)
[[5]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L96-R97)
[[6]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L107-R114)
[[7]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L124-R124)
[[8]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L135-R143)
[[9]](diffhunk://#diff-3a1259e160a4dfa5fe49dfe739fbdb986c0d0a2220a709882ea48d3ae1b8f911L167-R167)

These changes collectively modernize the codebase and prepare it for
future Go developments by using the idiomatic `any` type.
2025-08-28 16:53:19 +08:00

216 lines
9.0 KiB
Go

// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package ghttp provides powerful http server and simple client implements.
package ghttp
import (
"net/http"
"reflect"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/net/ghttp/internal/graceful"
"github.com/gogf/gf/v2/net/goai"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gsession"
"github.com/gogf/gf/v2/os/gstructs"
"github.com/gogf/gf/v2/util/gtag"
)
type (
// Server wraps the http.Server and provides more rich features.
Server struct {
instance string // Instance name of current HTTP server.
config ServerConfig // Server configuration.
plugins []Plugin // Plugin array to extend server functionality.
servers []*graceful.Server // Underlying http.Server array.
serverCount *gtype.Int // Underlying http.Server number for internal usage.
closeChan chan struct{} // Used for underlying server closing event notification.
serveTree map[string]any // The route maps tree.
serveCache *gcache.Cache // Server caches for internal usage.
routesMap map[string][]*HandlerItem // Route map mainly for route dumps and repeated route checks.
statusHandlerMap map[string][]HandlerFunc // Custom status handler map.
sessionManager *gsession.Manager // Session manager.
openapi *goai.OpenApiV3 // The OpenApi specification management object.
serviceMu sync.Mutex // Concurrent safety for operations of attribute service.
service gsvc.Service // The service for Registry.
registrar gsvc.Registrar // Registrar for service register.
}
// Router object.
Router struct {
Uri string // URI.
Method string // HTTP method
Domain string // Bound domain.
RegRule string // Parsed regular expression for route matching.
RegNames []string // Parsed router parameter names.
Priority int // Just for reference.
}
// RouterItem is just for route dumps.
RouterItem struct {
Handler *HandlerItem // The handler.
Server string // Server name.
Address string // Listening address.
Domain string // Bound domain, eg: example.com
Type HandlerType // Route handler type.
Middleware string // Bound middleware.
Method string // Handler method name, eg: get, post.
Route string // Route URI, eg: /api/v1/user/{id}.
Priority int // Just for reference.
IsServiceHandler bool // Is a service handler.
}
// HandlerFunc is request handler function.
HandlerFunc = func(r *Request)
// handlerFuncInfo contains the HandlerFunc address and its reflection type.
handlerFuncInfo struct {
Func HandlerFunc // Handler function address.
Type reflect.Type // Reflect type information for current handler, which is used for extensions of the handler feature.
Value reflect.Value // Reflect value information for current handler, which is used for extensions of the handler feature.
IsStrictRoute bool // Whether strict route matching is enabled.
ReqStructFields []gstructs.Field // Request struct fields.
}
// HandlerItem is the registered handler for route handling,
// including middleware and hook functions.
HandlerItem struct {
// Unique handler item id mark.
// Note that the handler function may be registered multiple times as different handler items,
// which have different handler item id.
Id int
Name string // Handler name, which is automatically retrieved from runtime stack when registered.
Type HandlerType // Handler type: object/handler/middleware/hook.
Info handlerFuncInfo // Handler function information.
InitFunc HandlerFunc // Initialization function when request enters the object (only available for object register type).
ShutFunc HandlerFunc // Shutdown function when request leaves out the object (only available for object register type).
Middleware []HandlerFunc // Bound middleware array.
HookName HookName // Hook type name, only available for the hook type.
Router *Router // Router object.
Source string // Registering source file `path:line`.
}
// HandlerItemParsed is the item parsed from URL.Path.
HandlerItemParsed struct {
Handler *HandlerItem // Handler information.
Values map[string]string // Router values parsed from URL.Path.
}
// ServerStatus is the server status enum type.
ServerStatus = int
// HookName is the route hook name enum type.
HookName string
// HandlerType is the route handler enum type.
HandlerType string
// Listening file descriptor mapping.
// The key is either "http" or "https" and the value is its FD.
listenerFdMap = map[string]string
// internalPanic is the custom panic for internal usage.
internalPanic string
)
const (
// FreePortAddress marks the server listens using random free port.
FreePortAddress = graceful.FreePortAddress
)
const (
HeaderXUrlPath = "x-url-path" // Used for custom route handler, which does not change URL.Path.
HookBeforeServe HookName = "HOOK_BEFORE_SERVE" // Hook handler before route handler/file serving.
HookAfterServe HookName = "HOOK_AFTER_SERVE" // Hook handler after route handler/file serving.
HookBeforeOutput HookName = "HOOK_BEFORE_OUTPUT" // Hook handler before response output.
HookAfterOutput HookName = "HOOK_AFTER_OUTPUT" // Hook handler after response output.
DefaultServerName = "default"
DefaultDomainName = "default"
HandlerTypeHandler HandlerType = "handler"
HandlerTypeObject HandlerType = "object"
HandlerTypeMiddleware HandlerType = "middleware"
HandlerTypeHook HandlerType = "hook"
ServerStatusStopped = graceful.ServerStatusStopped
ServerStatusRunning = graceful.ServerStatusRunning
)
const (
supportedHttpMethods = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
defaultMethod = "ALL"
routeCacheDuration = time.Hour
ctxKeyForRequest gctx.StrKey = "gHttpRequestObject"
contentTypeXml = "text/xml"
contentTypeHtml = "text/html"
contentTypeJson = "application/json"
contentTypeJavascript = "application/javascript"
swaggerUIPackedPath = "/goframe/swaggerui"
responseHeaderTraceID = "Trace-ID"
specialMethodNameInit = "Init"
specialMethodNameShut = "Shut"
specialMethodNameIndex = "Index"
defaultEndpointPort = 80
noPrintInternalRoute = "internalMiddlewareServerTracing"
)
const (
exceptionExit internalPanic = "exit"
exceptionExitAll internalPanic = "exit_all"
exceptionExitHook internalPanic = "exit_hook"
)
var (
// methodsMap stores all supported HTTP method.
// It is used for quick HTTP method searching using map.
methodsMap = make(map[string]struct{})
// serverMapping stores more than one server instances for current processes.
// The key is the name of the server, and the value is its instance.
serverMapping = gmap.NewStrAnyMap(true)
// serverRunning marks the running server counts.
// If there is no successful server running or all servers' shutdown, this value is 0.
serverRunning = gtype.NewInt()
// wsUpGrader is the default up-grader configuration for websocket.
wsUpGrader = websocket.Upgrader{
// It does not check the origin in default, the application can do it itself.
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// allShutdownChan is the event for all servers have done its serving and exit.
// It is used for process blocking purpose.
allShutdownChan = make(chan struct{}, 1000)
// serverProcessInitialized is used for lazy initialization for server.
// The process can only be initialized once.
serverProcessInitialized = gtype.NewBool()
// gracefulEnabled is used for a graceful reload feature, which is false in default.
gracefulEnabled = false
// defaultValueTags are the struct tag names for default value storing.
defaultValueTags = []string{gtag.DefaultShort, gtag.Default}
)
var (
// ErrNeedJsonBody is the error that indicates the request body content should be JSON format.
ErrNeedJsonBody = gerror.NewWithOption(gerror.Option{
Text: "the request body content should be JSON format",
Code: gcode.CodeInvalidRequest,
})
)