TangSengDaoDao / TangSengDaoDaoServer

高颜值 IM 即时通讯,聊天
https://tsdaodao.com
Apache License 2.0
2.07k stars 268 forks source link

请教关于源码中 wkhttp 的设计 #94

Open QingsiLiu opened 4 days ago

QingsiLiu commented 4 days ago

在看大佬源码时看到 pkg 目录下的 wkhttp 时有些困惑,具体代码为:

// WKHttp WKHttp
type WKHttp struct {
    r    *gin.Engine
    pool sync.Pool
}

我的理解是通过封装 gin 框架,来将 gin.Context 使用 sync.Pool 进行管理,减少内存分配,提高性能。但是 gin 框架本身对于 Context 就是使用 sync.Pool 来进行管理的,源码:

// ServeHTTP conforms to the http.Handler interface.
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    c := engine.pool.Get().(*Context)
    c.writermem.reset(w)
    c.Request = req
    c.reset()

    engine.handleHTTPRequest(c)

    engine.pool.Put(c)
}

这样的设计带来了一些额外的代码封装,是出于什么考虑呢?

tangtaoit commented 4 days ago

主要是让gin.Context 变成自己的wkhttp.Context. 这样就可以在wkhttp.Context封装许多自己的通用逻辑。

比如错误返回,权限判断等

image
QingsiLiu commented 4 days ago

好的,明白!谢谢解答