Does anyone have any examples of dependency injection via context in Gin or something similar?

polaris · · 632 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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&#39;ve been attempting to implement something along those lines but with mgo instead. I have something sort of working, but it doesn&#39;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&#39;d say that was a bad approach overall? Do you have any best practice examples?</p></pre>unitedcreatures: <pre><p>Well I won&#39;t say that it&#39;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&#39;s inside the handler func already! w.Write(obj.YourMethod()) } } // in the wireup obj := &amp;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>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

632 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传