<p>Hello! I'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'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 <-resultCh:
case <-timeoutCh:
}
}
func DoActualWork(w, r, c) {
// We do some really hard work here
fmt.Fprintf(w, "Hey looks like we're done")
c <- true
}
</code></pre>
<p><a href="http://blog.golang.org/go-concurrency-patterns-timing-out-and" rel="nofollow">Here's a link</a> </p>
<p><a href="https://blog.golang.org/pipelines" rel="nofollow">And here'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传