Server side timeouts for long running requests in net/http

agolangf · · 673 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello! I&#39;m trying to explicitly set timeouts for requests on my net/http server. If a request takes longer than 15 minutes it needs to close the connection. Looking at the documentation, I couldn&#39;t find anything like this. </p> <p>Has anyone done something like this in golang?</p> <hr/>**评论:**<br/><br/>010a: <pre><p>Something like</p> <pre><code>func HandlerFunction(w http.ResponseWriter, r *http.Request) { timeoutCh := time.After(15 * time.Minutes) resultCh := make(chan bool, 1) go DoActualWork(w, r, resultCh) select { case &lt;-resultCh: case &lt;-timeoutCh: } } func DoActualWork(w, r, c) { // We do some really hard work here fmt.Fprintf(w, &#34;Hey looks like we&#39;re done&#34;) c &lt;- true } </code></pre> <p><a href="http://blog.golang.org/go-concurrency-patterns-timing-out-and" rel="nofollow">Here&#39;s a link</a> </p> <p><a href="https://blog.golang.org/pipelines" rel="nofollow">And here&#39;s another</a></p></pre>bourbondog: <pre><p>This works. Do you know if something like this is already supported by the API?</p></pre>shirro: <pre><p>Instead of passing a timer, another option is to use <a href="https://godoc.org/golang.org/x/net/context" rel="nofollow">x/net/context</a> which has a few extra benefits. I have been passing contexts to my handlers, mainly to pass values from middleware, but you can also add a timeout using WithTimeout and then select on the channel returned by ctx.Done().</p> <p><a href="http://blog.golang.org/context" rel="nofollow">http://blog.golang.org/context</a></p></pre>

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

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