I want to keep my Golang language web server working regardless of an error happens or not. How to keep running it always?
We have to inspect an always-on server from 2 perspectives:
For the first, you don't have to do anything special. If your handler panics, it will not blow your whole server, the http server will recover from that. It will only stop serving that specific request. Of course you can create your own handler which calls other handlers and recovers on panic and handle it in an intelligent way, but this is not a requirement.
One thing to note here: a Go app ends when the main
goroutine ends (that is: the main()
function returns). So even though goroutines serving requests are protected, if your main goroutine would end (e.g.
panic), your app would still exit.
For the second, it's not really Go related. For example if you're on linux, simply install / register your compiled Go executable as a service, properly configured to have it restarted should it exit or crash.
For example in Ubuntu which uses systemd for service configuration, the following minimal service descriptor would fulfill your wishes:
[Unit]
Description=My Always-on Service
[Service]
Restart=always
Type=simple
ExecStart=/path/to/your/app -some=params passed
[Install]
WantedBy=multi-user.target
Put the above text in a file e.g. /etc/systemd/system/myservice.service
, and you can enable and start it with:
sudo systemctl enable myservice.service
sudo systemctl start myservice.service
The first command places a symlink to the proper folder to have it auto-started on system startup. The second command starts it right now.
To verify if it's running, type:
sudo systemctl status myservice.service
(You can omit the .service
extension in most cases.)
Now whenever your app crashes, or the OS gets restarted, your app will be automatically started / restarted.
Further reading and tutorials for systemd:
How To Use Systemctl to Manage Systemd Services and Units
Systemd Essentials: Working with Services, Units, and the Journal
Convert "run at startup" script from upstart to systemd for Ubuntu 16
systemd: Writing and Enabling a Service
There are few things which you can do. Such as,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With