gin 是一个流行的 golang webserver 的框架。https://github.com/gin-gonic/gin
HandlerFunctype HandlerFunc func(*Context)
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
*gin.Context
context.Contextgin.Context
context.WithValuekey,valctxContextgin.ContextSetctxinterface{}string
// 标准库 函数
func WithValue(parent Context, key, val interface{}) Context
// gin.Context 方法
func (c *Context) Set(key string, value interface{})
context.Context.Value(key interface{}) interface{}gin.Context.Get(key string) interface{}bool 类型的 exists
// 标准库
db := ctx.Value("db"
// gin
// db := c.Value("db") // 实现了 Context 接口, 可以。
db, exists := c.Get("db")
if !exists {
return
}
context iocgin context ioc
// 标准库
//
func save(ctx context.Context) {
// ...
}
// gin
func main() {
r := gin.Default()
r.Use(GinContextIoC) // 使用 middleware 的方式在 context 中注入与传递
// ...
}
完整 demo
这是一个实现了 gin context ioc 容器的 demo
golang demo 源代码 https://tangx.in/images/post/2021/07/28/gin-context-ioc/gin-context-ioc.go