Jam*_*nne 10 signals go unix-socket
我有一个Go程序托管一个简单的HTTP服务,localhost:8080因此我可以nginx通过proxy_pass指令将我的公共主机连接到它,作为反向代理服务我网站的部分请求.这一切都很好,没有问题.
我想将Go程序转换为在Unix域套接字而不是本地TCP套接字上托管HTTP服务,以提高安全性并减少TCP的不必要的协议开销.
问题:问题是bind()即使在程序终止之后,Unix域套接字仍然无法重用.第二次(以及之后)我运行Go程序它会以致命错误退出"address already in use".
unlink()服务器关闭时,常见的做法是Unix域套接字(即删除文件).但是,这在Go中很棘手.我的第一次尝试是defer在我的主函数中使用该语句(见下文),但如果我用CTRL-C这样的信号中断进程,它就不会运行.我想这是可以预料的.令人失望,但并非出乎意料.
问题:unlink()当服务器进程关闭时(优雅或不正常),是否有关于套接字的最佳实践?
这是我的一部分func main(),启动服务器监听参考:
// Create the HTTP server listening on the requested socket:
l, err := net.Listen("unix", "/tmp/mysocket")
if err != nil {
log.Fatal(err)
} else {
// Unix sockets must be unlink()ed before being reused again.
// Unfortunately, this defer is not run when a signal is received, e.g. CTRL-C.
defer func() {
os.Remove("/tmp/mysocket")
}()
log.Fatal(http.Serve(l, http.HandlerFunc(indexHtml)))
}
Run Code Online (Sandbox Code Playgroud)
这是我使用的完整解决方案.我在我的问题中发布的代码是一个简化版本,用于明确的演示目的.
// Create the socket to listen on:
l, err := net.Listen(socketType, socketAddr)
if err != nil {
log.Fatal(err)
return
}
// Unix sockets must be unlink()ed before being reused again.
// Handle common process-killing signals so we can gracefully shut down:
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, os.Kill, syscall.SIGTERM)
go func(c chan os.Signal) {
// Wait for a SIGINT or SIGKILL:
sig := <-c
log.Printf("Caught signal %s: shutting down.", sig)
// Stop listening (and unlink the socket if unix type):
l.Close()
// And we're done:
os.Exit(0)
}(sigc)
// Start the HTTP server:
log.Fatal(http.Serve(l, http.HandlerFunc(indexHtml)))
Run Code Online (Sandbox Code Playgroud)
我当然希望这是一个优秀而有效的Go代码,可以让Go作者感到自豪.对我来说当然看起来如此.如果不是,那将是我的尴尬.:)
对于任何好奇的人来说,这是https://github.com/JamesDunne/go-index-html的一部分,它是一个简单的HTTP目录列表生成器,具有一些额外的功能,Web服务器不会为您提供开箱即用的功能.
| 归档时间: |
|
| 查看次数: |
6275 次 |
| 最近记录: |