douzhuoxia0587 2017-04-27 06:30
浏览 48
已采纳

继续将Go Server作为后台进程运行

I want to keep my Golang language web server working regardless of an error happens or not. How to keep running it always?

  • 写回答

2条回答 默认 最新

  • doubi1910 2017-04-27 06:58
    关注

    We have to inspect an always-on server from 2 perspectives:

    1. Handle / tolerate errors that occur during serving requests
    2. Restart the server app if it crashes or gets killed

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器