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 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数