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 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable