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 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!