在文件保存时重新启动 Golang 服务器的最佳方法是什么?

huangapple go评论97阅读模式
英文:

Best way to restart a golang server on file saves

问题

我有一个API代码,它存在于我的$GOPATH中,但主文件在系统的其他位置。我想在某些文件保存时让我的主文件退出并重新启动。我最接近的方法是使用findentr的组合:

find $GOPATH/github.com/example/example -path $GOPATH/example/example/vendor -prune -o -name '*.go' -print | entr -r go run /vagrant/script/api/main.go

但是由于某种原因,在重新启动之前,entr无法关闭服务,导致出现错误消息:

ListenAndServe: listen tcp 127.0.0.1:1456: bind: address already in use

我希望能够使用任何允许实时重新加载Go服务器的解决方案,但是配置/设置越简单越好,因为我希望在多个项目中重用该解决方案。

不确定这是否是一个问题,但我还应该注意到,我正在使用vagrant-fsnotify在主机机器上保存文件时,在Vagrant虚拟机中触发更改的文件。

英文:

I have API code written that exists in my $GOPATH but the main file is elsewhere on the system. I'm trying to get my main file to exit and start and again whenever certain files are saved. The closest I've gotten is by using a combination of find and entr:

find $GOPATH/github.com/example/example -path $GOPATH/example/example/vendor -prune -o -name '*.go' -print | entr -r go run /vagrant/script/api/main.go

But for some reason entr fails to shut the service down before starting it again resulting in the error message:

ListenAndServe: listen tcp 127.0.0.1:1456: bind: address already in use

Open to any solution that allows live reloading of the go server, but the less configuration/setup required the better as I'd like to reuse the solution in multiple projects.

Not sure this is an issue, but I should also note that I'm using vagrant-fsnotify to touch changed files in my Vagrant guest machine when saved on the host machine.

答案1

得分: 1

根据评论,您正在使用一个旧版本的entr,它只会终止go run进程,而您的Go程序仍然在运行。运行版本3.1或更新的entr还会向您的Go可执行文件发送终止信号,这应该可以解决问题。

如果可能的话,请升级entr到当前版本(3.6),或者至少升级到3.1+。如果不可能的话,一种解决方案是编写一个处理终止信号的包装程序。该程序将运行go run并监视终止信号。在接收到该信号后,您的包装程序将同时终止go run和您的Go程序。

英文:

Per the comments, you're using an old version of entr which is killing only the go run process, leaving your Go program still running. Running version 3.1 or newer of entr will also send the termination signal to your Go executable, which should resolve the issue.

If at all possible, upgrade entr to the current version (3.6), or at least 3.1+. If that's not possible, one solution would be to write a wrapper program that handles the termination signal for you. That program would run go run and watch for the termination signal. Upon receiving that signal, your wrapper would kill both go run and your Go program.

huangapple
  • 本文由 发表于 2017年2月24日 05:47:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/42426800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定