Files
gf/net/ghttp/ghttp_server_router_serve.go
Lance Add d8a173d9f0 feat(instance): migrate instance containers to type-safe generics (#4617)
### 变更说明

本次重构将项目中用于**实例管理的容器**从 `StrAnyMap`/`IntAnyMap` 迁移到类型安全的泛型实现
`KVMapWithChecker`,同时将相关的 `glist.List` 和 `gqueue.Queue`
替换为对应的泛型版本,以提高实例管理的类型安全性。并且减少原先代码中的大量类型断言,提高性能。

### 前因

目前`goframe`中大量使用了包含`any`的容器,然后通过断言去转换类型,麻烦且影响性能,尤其是对`gdb/gredis/glog`等需要高频获取`instance`实例的组件影响较大。最近几个版本中gf完成了数据结构容器的泛型化改造,以及我最近解决了其中几个泛型容器对于`typed
nil`过滤的问题,所以可以逐步迁移这些实例容器到泛型容器,减少断言优化性能

### 主要改进

#### 1. 实例容器泛型化

以下模块的实例管理容器已迁移到泛型实现:

**核心实例管理**:
- `database/gdb`: 数据库实例容器 → `KVMap[string, DB]`
- `database/gredis`: Redis 实例容器 → `KVMap[string, *Redis]`
- `database/gredis`: Redis 配置容器 → `KVMap[string, *Config]`
- `os/gcfg`: 配置实例容器 → `KVMap[string, *Config]`
- `os/glog`: 日志实例容器 → `KVMap[string, *Logger]`
- `os/gview`: 视图实例容器 → `KVMap[string, *View]`
- `i18n/gi18n`: 国际化实例容器 → `KVMap[string, *Manager]`

**网络服务实例**:
- `net/ghttp`: HTTP 服务器容器 → `KVMap[string, *Server]`
- `net/gtcp`: TCP 服务器容器 → `KVMap[any, *Server]`
- `net/gudp`: UDP 服务器容器 → `KVMap[string, *Server]`

**其他实例容器**:
- `os/gres`: 资源实例容器 → `KVMap[string, *Resource]`
- `os/gfpool`: 文件池容器 → `KVMap[string, *Pool]`
- `os/gspath`: 路径搜索容器 → `KVMap[string, *SPath]`
- `net/gtcp`: 连接池容器 → `KVMap[string, *gpool.Pool]`

#### 2. 相关数据结构泛型化

- `os/gfsnotify`: 回调列表 → `TList[*Callback]`,事件队列 → `TQueue[*Event]`
- `os/grpool`: 任务队列 → `TList[*localPoolItem]`
- `os/gcache`: 事件队列 → `TList[*adapterMemoryEvent]`
- `net/ghttp`: 解析项列表 → `TList[*HandlerItemParsed]`
- `os/gproc`: 消息队列 → `TQueue[*MsgRequest]`
- `os/gmlock`: 锁映射 → `KVMap[string, *sync.RWMutex]`

### 技术实现

1. **引入检查器函数**: 为每个实例容器添加 `checker` 函数用于空值检测
2. **消除类型断言**: 实例获取时无需 `v.(*Type)` 转换
3. **明确函数签名**: `GetOrSetFuncLock` 的回调从 `func() any` 改为 `func() T`

### 使用示例

#### 实例容器的变更

**变更前**:
```go
// 旧的实例管理方式
var instances = gmap.NewStrAnyMap(true)

func Instance(name string) *Logger {
    v := instances.GetOrSetFuncLock(name, func() any {
        return New()
    })
    return v.(*Logger)  // 需要类型断言
}
```


**变更后**:
```go
// 新的泛型实例容器
var (
    checker   = func(v *Logger) bool { return v == nil }
    instances = gmap.NewKVMapWithChecker[string, *Logger](checker, true)
)

func Instance(name string) *Logger {
    return instances.GetOrSetFuncLock(name, New)  // 直接返回,无需断言
}
```


#### 队列容器的变更

**变更前**:
```go
// 旧的队列方式
events := gqueue.New()
events.Push(&Event{Path: "/tmp/file"})

if v := events.Pop(); v != nil {
    event := v.(*Event)  // 需要类型断言
    handleEvent(event)
}
```


**变更后**:
```go
// 新的泛型队列
events := gqueue.NewTQueue[*Event]()
events.Push(&Event{Path: "/tmp/file"})

if event := events.Pop(); event != nil {
    handleEvent(event)  // event 已是 *Event 类型
}
```


### 收益

-  **编译时类型安全**: 实例容器的类型错误在编译期捕获
-  **消除运行时断言**: 避免类型断言带来的 panic 风险
-  **提升代码可读性**: 实例管理逻辑更清晰
-  **改善开发体验**: IDE 类型提示和代码补全更准确

### 性能权衡

**编译时**:
- 泛型实例化会增加编译时间和二进制体积
- 预估编译时间增加 5-15%,二进制体积增加约 1-2MB

**运行时**:
- 减少类型断言的反射开销
- 提升实例获取等热点路径的性能
2026-01-16 15:23:13 +08:00

323 lines
10 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
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/gogf/gf/v2/container/glist"
"github.com/gogf/gf/v2/encoding/gurl"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/util/gmeta"
)
// handlerCacheItem is an item just for internal router searching cache.
type handlerCacheItem struct {
parsedItems []*HandlerItemParsed
serveItem *HandlerItemParsed
hasHook bool
hasServe bool
}
// serveHandlerKey creates and returns a handler key for router.
func (s *Server) serveHandlerKey(method, path, domain string) string {
if len(domain) > 0 {
domain = "@" + domain
}
if method == "" {
return path + strings.ToLower(domain)
}
return strings.ToUpper(method) + ":" + path + strings.ToLower(domain)
}
// getHandlersWithCache searches the router item with cache feature for a given request.
func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*HandlerItemParsed, serveItem *HandlerItemParsed, hasHook, hasServe bool) {
var (
ctx = r.Context()
method = r.Method
path = r.URL.Path
host = r.GetHost()
)
// In case of, eg:
// Case 1:
// GET /net/http
// r.URL.Path : /net/http
// r.URL.RawPath : (empty string)
// Case 2:
// GET /net%2Fhttp
// r.URL.Path : /net/http
// r.URL.RawPath : /net%2Fhttp
if r.URL.RawPath != "" {
path = r.URL.RawPath
}
// Special http method OPTIONS handling.
// It searches the handler with the request method instead of OPTIONS method.
if method == http.MethodOptions {
if v := r.Header.Get("Access-Control-Request-Method"); v != "" {
method = v
}
}
// Search and cache the router handlers.
if xUrlPath := r.Header.Get(HeaderXUrlPath); xUrlPath != "" {
path = xUrlPath
}
var handlerCacheKey = s.serveHandlerKey(method, path, host)
value, err := s.serveCache.GetOrSetFunc(ctx, handlerCacheKey, func(ctx context.Context) (any, error) {
parsedItems, serveItem, hasHook, hasServe = s.searchHandlers(method, path, host)
if parsedItems != nil {
return &handlerCacheItem{parsedItems, serveItem, hasHook, hasServe}, nil
}
return nil, nil
}, routeCacheDuration)
if err != nil {
intlog.Errorf(ctx, `%+v`, err)
}
if value != nil {
item := value.Val().(*handlerCacheItem)
return item.parsedItems, item.serveItem, item.hasHook, item.hasServe
}
return
}
// searchHandlers retrieve and returns the routers with given parameters.
// Note that the returned routers contain serving handler, middleware handlers and hook handlers.
func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*HandlerItemParsed, serveItem *HandlerItemParsed, hasHook, hasServe bool) {
if len(path) == 0 {
return nil, nil, false, false
}
// In case of double '/' URI, for example:
// /user//index, //user/index, //user//index//
var previousIsSep = false
for i := 0; i < len(path); {
if path[i] == '/' {
if previousIsSep {
path = path[:i] + path[i+1:]
continue
} else {
previousIsSep = true
}
} else {
previousIsSep = false
}
i++
}
// Split the URL.path to separate parts.
var array []string
if strings.EqualFold("/", path) {
array = []string{"/"}
} else {
array = strings.Split(path[1:], "/")
}
var (
lastMiddlewareElem *glist.TElement[*HandlerItemParsed]
parsedItemList = glist.NewT[*HandlerItemParsed]()
repeatHandlerCheckMap = make(map[int]struct{}, 16)
)
// The default domain has the most priority when iteration.
// Please see doSetHandler if you want to get known about the structure of serveTree.
for _, domainItem := range []string{DefaultDomainName, domain} {
p, ok := s.serveTree[domainItem]
if !ok {
continue
}
// Make a list array with a capacity of 16.
lists := make([]*glist.List, 0, 16)
for i, part := range array {
// Add all lists of each node to the list array.
if v, ok := p.(map[string]any)["*list"]; ok {
lists = append(lists, v.(*glist.List))
}
if v, ok := p.(map[string]any)[part]; ok {
// Loop to the next node by certain key name.
p = v
if i == len(array)-1 {
if v, ok := p.(map[string]any)["*list"]; ok {
lists = append(lists, v.(*glist.List))
break
}
}
} else if v, ok := p.(map[string]any)["*fuzz"]; ok {
// Loop to the next node by fuzzy node item.
p = v
}
if i == len(array)-1 {
// It here also checks the fuzzy item,
// for rule case like: "/user/*action" matches to "/user".
if v, ok := p.(map[string]any)["*fuzz"]; ok {
p = v
}
// The leaf must have a list item. It adds the list to the list array.
if v, ok := p.(map[string]any)["*list"]; ok {
lists = append(lists, v.(*glist.List))
}
}
}
// OK, let's loop the result list array, adding the handler item to the result handler result array.
// As the tail of the list array has the most priority, it iterates the list array from its tail to head.
for i := len(lists) - 1; i >= 0; i-- {
for e := lists[i].Front(); e != nil; e = e.Next() {
item := e.Value.(*HandlerItem)
// Filter repeated handler items, especially the middleware and hook handlers.
// It is necessary, do not remove this checks logic unless you really know how it is necessary.
//
// The `repeatHandlerCheckMap` is used for repeat handler filtering during handler searching.
// As there are fuzzy nodes, and the fuzzy nodes have both sub-nodes and sub-list nodes, there
// may be repeated handler items in both sub-nodes and sub-list nodes. It here uses handler item id to
// identify the same handler item that registered.
//
// The same handler item is the one that is registered in the same function doSetHandler.
// Note that, one handler function(middleware or hook function) may be registered multiple times as
// different handler items using function doSetHandler, and they have different handler item id.
//
// Note that twice, the handler function may be registered multiple times as different handler items.
if _, isRepeatedHandler := repeatHandlerCheckMap[item.Id]; isRepeatedHandler {
continue
} else {
repeatHandlerCheckMap[item.Id] = struct{}{}
}
// Serving handler can only be added to the handler array just once.
// The first route item in the list has the most priority than the rest.
// This ignoring can implement route overwritten feature.
if hasServe {
switch item.Type {
case HandlerTypeHandler, HandlerTypeObject:
continue
}
}
if item.Router.Method == defaultMethod || item.Router.Method == method {
// Note the rule having no fuzzy rules: len(match) == 1
if match, err := gregex.MatchString(item.Router.RegRule, path); err == nil && len(match) > 0 {
parsedItem := &HandlerItemParsed{item, nil}
// If the rule contains fuzzy names,
// it needs paring the URL to retrieve the values for the names.
if len(item.Router.RegNames) > 0 {
if len(match) > len(item.Router.RegNames) {
parsedItem.Values = make(map[string]string)
// It there repeated names, it just overwrites the same one.
for i, name := range item.Router.RegNames {
parsedItem.Values[name], _ = gurl.Decode(match[i+1])
}
}
}
switch item.Type {
// The serving handler can be added just once.
case HandlerTypeHandler, HandlerTypeObject:
hasServe = true
serveItem = parsedItem
parsedItemList.PushBack(parsedItem)
// The middleware is inserted before the serving handler.
// If there are multiple middleware, they're inserted into the result list by their registering order.
// The middleware is also executed by their registered order.
case HandlerTypeMiddleware:
if lastMiddlewareElem == nil {
lastMiddlewareElem = parsedItemList.PushFront(parsedItem)
} else {
lastMiddlewareElem = parsedItemList.InsertAfter(lastMiddlewareElem, parsedItem)
}
// HOOK handler, just push it back to the list.
case HandlerTypeHook:
hasHook = true
parsedItemList.PushBack(parsedItem)
default:
panic(gerror.Newf(`invalid handler type %s`, item.Type))
}
}
}
}
}
}
if parsedItemList.Len() > 0 {
var index = 0
parsedItems = make([]*HandlerItemParsed, parsedItemList.Len())
for e := parsedItemList.Front(); e != nil; e = e.Next() {
parsedItems[index] = e.Value
index++
}
}
return
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (h *HandlerItem) MarshalJSON() ([]byte, error) {
switch h.Type {
case HandlerTypeHook:
return json.Marshal(
fmt.Sprintf(
`%s %s:%s (%s)`,
h.Router.Uri,
h.Router.Domain,
h.Router.Method,
h.HookName,
),
)
case HandlerTypeMiddleware:
return json.Marshal(
fmt.Sprintf(
`%s %s:%s (MIDDLEWARE)`,
h.Router.Uri,
h.Router.Domain,
h.Router.Method,
),
)
default:
return json.Marshal(
fmt.Sprintf(
`%s %s:%s`,
h.Router.Uri,
h.Router.Domain,
h.Router.Method,
),
)
}
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (h *HandlerItemParsed) MarshalJSON() ([]byte, error) {
return json.Marshal(h.Handler)
}
// GetMetaTag retrieves and returns the metadata value associated with the given key from the request struct.
// The meta value is from struct tags from g.Meta/gmeta.Meta type.
func (h *HandlerItem) GetMetaTag(key string) string {
if h != nil && h.Info.Type != nil && h.Info.Type.NumIn() == 2 {
metaValue := gmeta.Get(h.Info.Type.In(1), key)
if metaValue != nil {
return metaValue.String()
}
}
return ""
}
// GetMetaTag retrieves and returns the metadata value associated with the given key from the request struct.
// The meta value is from struct tags from g.Meta/gmeta.Meta type.
// For example:
//
// type GetMetaTagReq struct {
// g.Meta `path:"/test" method:"post" summary:"meta_tag" tags:"meta"`
// // ...
// }
//
// r.GetServeHandler().GetMetaTag("summary") // returns "meta_tag"
// r.GetServeHandler().GetMetaTag("method") // returns "post"
func (h *HandlerItemParsed) GetMetaTag(key string) string {
if h == nil || h.Handler == nil {
return ""
}
return h.Handler.GetMetaTag(key)
}