Do you use context in most of the functions?

xuanbao · · 475 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>In a web API, I have a logger stored in context. Do I pass the context to the functions that access databases?</p> <p>In these cases, does it mean I should always use context as the first argument?</p> <hr/>**评论:**<br/><br/>tv64738: <pre><p>Databases specifically are an example of where you really should pass in a context. Imagine a slow and expensive query being performed on behalf of a user who has already lost interest and closed the browser tab.</p> <p><a href="https://golang.org/pkg/database/sql/#DB.QueryContext" rel="nofollow">https://golang.org/pkg/database/sql/#DB.QueryContext</a></p></pre>jcchavezs: <pre><p>It is a good practice to pass the context as first argument and most of the libraries are moving in that direction. Worth to read <a href="https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39" rel="nofollow">https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39</a></p></pre>tree_hau5: <pre><p>I don&#39;t ever pass anything to any function unless I know I am explicitly going to need it. That said, I like the &#34;opt-in&#34; aspect of most libraries by having FunctionName and also FunctionNameContext</p></pre>tv64738: <pre><p>That &#34;opt-in&#34; thing was largely dictated by FunctionName predating existence of context. You might not want to pick that as a design goal.</p></pre>tex0: <pre><p>Agreed, we&#39;re moving to passing a context as the first parameter in all of our internal and open source projects.</p> <p>While I don&#39;t like every aspect of the Context pattern it still solves some real world problems in an acceptable way.</p></pre>faiface: <pre><p>Aside from what other people suggested, I think it&#39;s also worth to read my older blog post:</p> <p><a href="https://faiface.github.io/post/context-should-go-away-go2/" rel="nofollow">https://faiface.github.io/post/context-should-go-away-go2/</a></p> <p>Many people (I think most) agreed with me at the time.</p></pre>tv64738: <pre><p>Yes Go 2 should see if context can be cleaned up. No we don&#39;t all agree with every single thing in your article.</p> <p>To pick a sample nit:</p> <blockquote> <p>but it’s harder to cancel a sub-tree</p> </blockquote> <p>That&#39;s exactly what context makes easy!</p> <p>Most importantly, <code>context</code> is like <code>gofmt</code>. You don&#39;t have to love every single design decision in it, but you gotta love agreeing on a single thing.</p></pre>faiface: <pre><p>If you read carefully, the fact that context makes cancelling a sub-tree easy is exactly what I said in the article.</p></pre>

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

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