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?
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