英文:
get notified when http.Server starts listening
问题
当我查看net/http服务器接口时,我没有看到明显的方法来在http.Server启动并开始监听时得到通知并做出反应:
ListenAndServe(":8080", nil)
该函数直到服务器实际关闭才返回。我还查看了Server类型,但似乎没有任何可以让我接入该时机的东西。一些函数或通道会很好,但我没有看到任何相关的内容。
是否有任何方法可以让我检测到这个事件,或者我只能通过睡眠足够长的时间来模拟它?
英文:
When I look at the net/http server interface, I don't see an obvious way to get notified and react when the http.Server comes up and starts listening:
ListenAndServe(":8080", nil)
The function doesn't return until the server actually shuts down. I also looked at the Server type, but there doesn't appear to be anything that lets me tap into that timing. Some function or a channel would have been great but I don't see any.
Is there any way that will let me detect that event, or am I left to just sleeping "enough" to fake it?
答案1
得分: 18
ListenAndServe是一个辅助函数,它打开一个监听套接字,然后在该套接字上提供连接。在你的应用程序中直接编写以下代码以信号化套接字已打开:
l, err := net.Listen("tcp", ":8080")
if err != nil {
// 处理错误
}
// 信号化服务器已开启。
if err := http.Serve(l, rootHandler); err != nil {
// 处理错误
}
如果信号化步骤不阻塞,那么http.Serve将轻松消耗监听套接字上的任何积压。
相关问题:https://stackoverflow.com/a/32742904/5728991
英文:
ListenAndServe is a helper function that opens a listening socket and then serves connections on that socket. Write the code directly in your application to signal when the socket is open:
l, err := net.Listen("tcp", ":8080")
if err != nil {
// handle error
}
// Signal that server is open for business.
if err := http.Serve(l, rootHandler); err != nil {
// handle error
}
If the signalling step does not block, then http.Serve will easily consume any backlog on the listening socket.
Related question: https://stackoverflow.com/a/32742904/5728991
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论