func main() {
var serverA = &http.Server{}
var serverB = &http.Server{}
// ... configure them as you wish: add endpoints
go serverA.ListenAndServe()
go serverB.ListenAndServe()
// create a channel to subscribe ctrl+c/SIGINT event
sigInterruptChannel := make(chan os.Signal, 1)
signal.Notify(sigInterruptChannel, os.Interrupt)
// block execution from continuing further until SIGINT comes
<-sigInterruptChannel
// create a context which will expire after 4 seconds of grace period
ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
defer cancel()
// ask to shutdown for both servers
go serverA.Shutdown(ctx)
go serverB.Shutdown(ctx)
// wait until ctx ends (which will happen after 4 seconds)
<-ctx.Done()
}
3条答案
按热度按时间jslywgbw1#
不你不能
但是,您可以在不同的端口上启动多个侦听器
mbzjlibv2#
下面是一个简单的工作示例:
qco9c6ql3#
您将需要不同的
*http.Server
示例,每个示例都单独配置(根据您的选择相同或不同)处理程序(或路由器)来为其端点提供服务。我们有一个更好的方法来组织并发的
http.Server
示例,同时仍然支持SIGINT
之后的优雅关闭,这是从shell发送到操作系统的信号。终端用户按下ctrl+c
时,操作系统进行编程。参见:
signal.Notify()
http.Shutdown(context.Context)