Pass database to json-rpc methods

polaris · · 490 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>So we already had a discussion with a lot of insights on the normal handler procedure, however, I am wondering what the best approach for json-rpc server is (using <a href="http://www.gorillatoolkit.org/pkg/rpc" rel="nofollow">http://www.gorillatoolkit.org/pkg/rpc</a>).</p> <p>Any ideas or reference projects which handle database access with the gorilla json-rpc without a global variable?</p> <hr/>**评论:**<br/><br/>mofirouz: <pre><p>On a side note, you might wanna checkout gRPC</p></pre>Pagedpuddle65: <pre><p>It might be just me since I&#39;m not too familiar with the framework you referenced but your question wasn&#39;t very clear to me. What exactly is the issue?</p></pre>ArghusSquare: <pre><p>Lets say I have the following</p> <pre><code>type HelloArgs struct { Who string } type HelloReply struct { Message string } type HelloService struct {} func (h *HelloService) Say(r *http.Request, args *HelloArgs, reply *HelloReply) error { reply.Message = &#34;Hello, &#34; + args.Who + &#34;!&#34; return nil } </code></pre> <p>Now I want to achieve something like <a href="http://www.alexedwards.net/blog/organising-database-access#using-an-interface" rel="nofollow">this</a> in my Say method. However based on the architecture of the framework I cannot use the env approach like http.HandleFunc(&#34;/books&#34;, env.booksIndex). So what&#39;s the best way to have something like this but without using a global variable like var DBCon *sql.DB</p></pre>Pagedpuddle65: <pre><p>You can add a property to your HelloService called &#34;db&#34;. When you initialize your service you&#39;ll set this property and then it can be accessed from within your methods. </p> <p>Does that fit the bill or am I still misunderstanding?</p></pre>ArghusSquare: <pre><p>Oh dear, I am stupid. I actually tried this, but it gave errors. Now I did it again and it works as expected, no clue what I did last time. Thanks</p></pre>Pagedpuddle65: <pre><p>Haha no sweat. </p></pre>

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

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