在http.Server开始侦听时收到通知 [英] get notified when http.Server starts listening
问题描述
当我查看net/http服务器界面时,没有看到一种明显的方法来通知并在http.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?
推荐答案
ListenAndServe是一个帮助程序函数,它打开一个侦听套接字,然后在该套接字上提供连接.直接在您的应用程序中编写代码,以在套接字打开时发出信号:
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
}
如果信令步骤未阻塞,则http.Serve将轻松消耗侦听套接字上的所有积压.
If the signalling step does not block, then http.Serve will easily consume any backlog on the listening socket.
相关问题: https://stackoverflow.com/a/32742904/5728991
这篇关于在http.Server开始侦听时收到通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!