<p>I noticed this Stack Overflow post the other day: <a href="http://stackoverflow.com/questions/35672842/go-and-gin-passing-around-struct-for-database-context" rel="nofollow">http://stackoverflow.com/questions/35672842/go-and-gin-passing-around-struct-for-database-context</a> </p>
<p>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! </p>
<p>Thanks in advance</p>
<hr/>**评论:**<br/><br/>unitedcreatures: <pre><p>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?</p></pre>ewanvalentine: <pre><p>So you'd say that was a bad approach overall? Do you have any best practice examples?</p></pre>unitedcreatures: <pre><p>Well I won't say that it's the best approach, but I get no problems with using closures like this:</p>
<pre><code>// 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
</code></pre></pre>birdsaresodumb: <pre><p><a href="https://github.com/facebookgo/inject" rel="nofollow">https://github.com/facebookgo/inject</a></p>
<p>Note: I got this link from a tweet saying specifically not to use it: <a href="https://twitter.com/peterbourgon/status/704416833693196290" rel="nofollow">https://twitter.com/peterbourgon/status/704416833693196290</a></p>
<p>Retweeted and commented upon by Dave Cheney, who knows a thing or two about Go.</p></pre>
Does anyone have any examples of dependency injection via context in Gin or something similar?
polaris · · 619 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传