douju9272 2018-11-26 17:24
浏览 208

在go http的自定义处理程序中传递* gorm.db实例的最佳实践

I am creating a custom web handler to handle my routes in an web application.

The handler is

type CustomHandler struct{
Db *gorm.DB
}

Then a receiver function:

func (h CustomHandler) Index() http.Handler {
   return http.handlerFunc(w http.ResponseWriter,r *http.Request){
   //Some code
   //use h.Db.Find() ,etc.
})

I am passing this to my router as

//In package 
customHandler := &CustomHandler{*gormInstance} //I've already got the instance
router.Handle("/someroute", customHandler.index() )

But a problem with this is gorm.DB instance, being a pointer will mutate once it pass through a route during one request. Do I have to generate different copies of the initial gorm instance? If so, How can I pass them through each routes on each requests?

  • 写回答

1条回答 默认 最新

  • dqba94394 2018-11-26 20:29
    关注

    According to Gorm documentation :

    All Chain Methods will clone and create a new DB object (shares one connection pool), GORM is safe for concurrent use by multiple goroutines.

    Gorm creates clones when it needs to automatically, there is no need to handle this manually. For more information check this page in the documentation: http://gorm.io/docs/method_chaining.html

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行