duanbo1659 2019-03-13 03:04
浏览 114

如何自动重启Go Web服务器(如果已停止)

I tried to apply a mechanism that allow the go web server to be automatically restarted when it's stopped.

The way I do it, by putting the server.ListenAndServe() inside an infinite loop. Since the .ListenAndServe() is blocking, I felt it's ok to do that. Here are the full code:

func main() {
    // ...

    isStarted := false
    for true {
        if isStarted {
            fmt.Println("===================================== RESTARTING WEB SERVER")
        }

        log.Println(server.ListenAndServe())
        isStarted = true

        time.Sleep(1 * time.Second)
    }
}

When I run the app, what happen is quite different than what I expected. The web server won't start.

Am I doing it wrong? or is there any better and correct way? Thank you in advance

===================================== RESTARTING WEB SERVER
2019/03/13 10:01:03 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:04 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:05 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:06 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:07 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:08 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:09 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:10 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:11 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:12 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:13 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:14 http: Server closed
  • 写回答

1条回答 默认 最新

  • dongzhanjuan5141 2019-03-13 05:48
    关注

    You need a process control system. That allows you to run and control a number of processes.

    Ex: Systemd, Supervisord

    Supervisord is a good option.

    Read the documentation on http://supervisord.org/

    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题