简体   繁体   中英

Best way to restart a golang server on file saves

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM