call Shutdown if ListenAndServe returns an error?

xuanbao · · 481 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Examples I&#39;ve found for the http Server.Shutdown method (new in go 1.8) do an abrupt panic or exit if ListenAndServe returns an error other than http.ErrServerClosed (for example, see the code below). </p> <p>This is fine if you shut down in response to an os.Interrupt signal (i.e. it won&#39;t be called). But what if ListenAndServe terminates for some other reason? Might there not be requests still in progress? Shouldn&#39;t you wait for them (e.g. by uncommenting the commented-out Shutdown in the code below)?</p> <pre><code>func main() { http.HandleFunc(&#34;/&#34;, func(w http.ResponseWriter, r *http.Request) { log.Println(&#34;Handler start.&#34;) time.Sleep(5 * time.Second) log.Println(&#34;Handler end.&#34;) }) srv := &amp;http.Server{Addr: &#34;:8081&#34;} go func() { done := make(chan os.Signal) signal.Notify(done, os.Interrupt) &lt;-done srv.Shutdown(context.Background()) }() err := srv.ListenAndServe() if err != nil &amp;&amp; err != http.ErrServerClosed { // srv.Shutdown(context.Background()) log.Fatalf(&#34;ListenAndServe error - %v&#34;, err) } } </code></pre> <hr/>**评论:**<br/><br/>ChristophBerger: <pre><p>I guess the reason lies in the &#34;crash early&#34; principle. If a process triggers unexpected errors, it may have gone into an unspecific state. Letting it continue to run may cause more damage (such as writing wrong data into the database) than crashing right away. </p></pre>georgekong: <pre><p>I suppose it&#39;s application-dependent. I&#39;m inclined to give my handlers the benefit of the doubt and let them finish.</p></pre>

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

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