I noticed this Stack Overflow post the other day: http://stackoverflow.com/questions/35672842/go-and-gin-passing-around-struct-for-database-context
I've been attempting to implement something along those lines but with mgo instead. I have something sort of working, but it doesn't feel too clean. So I was wondering if anyone had any examples or open-source projects which use this methodology? Much, much appreciated!
Thanks in advance
评论:
unitedcreatures:
ewanvalentine:Why to waste CPU cycles on field creation for each request and introduce new type of bug (injection failure) when you can use closures and wire everything up once on startup?
unitedcreatures:So you'd say that was a bad approach overall? Do you have any best practice examples?
birdsaresodumb:Well I won't say that it's the best approach, but I get no problems with using closures like this:
// handler code func GetMethodOutput(obj *yourObj) http.HandlerFunc { // return the func return func(w http.ResponseWriter, r *http.Request) { // no need to pass the obj anywhere - it's inside the handler func already! w.Write(obj.YourMethod()) } } // in the wireup obj := &yourObj{} handler := GetMethodOutput(obj) // use the handler as you would normally use http.HandlerFunc
https://github.com/facebookgo/inject
Note: I got this link from a tweet saying specifically not to use it: https://twitter.com/peterbourgon/status/704416833693196290
Retweeted and commented upon by Dave Cheney, who knows a thing or two about Go.
