duanbiao4025 2015-12-23 08:35
浏览 26
已采纳

如果阻塞,如何将http.Serve放在自己的goroutine中?

http.Serve either returns an error as soon as it is called or blocks if successfully executing.

How can I make it so that if it blocks it does so in its own goroutine? I currently have the following code:

func serveOrErr(l net.Listener, handler http.Handler) error {
    starting := make(chan struct{})
    serveErr := make(chan error)
    go func() {
        starting <- struct{}{}
        if err := http.Serve(l, handler); err != nil {
            serveErr <- err 
        }   
    }()
    <-starting

    select {
    case err := <-serveErr:
        return err
    default:
        return nil
    }
}

This seemed like a good start and works on my test machine but I believe that there are no guarantees that serveErr <- err would be called before case err := <-serveErr therefore leading to inconsistent results due to a data race if http.Serve were to produce an error.

  • 写回答

2条回答 默认 最新

  • donh61500 2015-12-23 09:20
    关注

    http.Serve either returns an error as soon as it is called or blocks if successfully executing

    This assumption is not correct. And I believe it rarely occurs. http.Serve calls net.Listener.Accept in the loop – an error can occur any time (socket closed, too many open file descriptors etc.). It's http.ListenAndServe, usually being used for running http servers, which often fails early while binding listening socket (no permissions, address already in use).

    In my opinion what you're trying to do is wrong, unless really your net.Listener.Accept is failing on the first call for some reason. Is it? If you want to be 100% sure your server is working, you could try to connect to it (and maybe actually transmit something), but once you successfully bound the socket I don't see it really necessary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程