doukuipei9938 2018-07-09 10:22
浏览 48
已采纳

如何在Go中查看或测试正常重启?

I serve HTTP over gin's https://github.com/fvbock/endless. I would like to see the differences from the basic HTTP server.

I've sent syscall.SIGUSR1 signal with:

syscall.Kill(getPid(), syscall.SIGUSR1)

The app doesn't exit, but I cannot detect the restart.

What I have to do is initialise new configurations to the app when the toml config file changes.

My code is as follows:

package main

import (
    "os"
    "fmt"
    "syscall"

    "github.com/gin-gonic/gin"
    "github.com/fvbock/endless"
    "github.com/BurntSushi/toml"
)

type Config struct {
    Age  int
    Cats []string
}

var cfg Config

func restart(c *gin.Context) {
    syscall.Kill(os.Getpid(), syscall.SIGUSR1)
}

func init() {
    toml.DecodeFile("config.toml", &cfg)
    fmt.Println("Testing", cfg)
}

func main() {
    router := gin.New()

    router.GET("/restart", restart)

    if err := endless.ListenAndServe("localhost:7777", router); err != nil {
        panic(err)
    }
}

When I hit the restart endpoint, I want the toml config printed out.

  • 写回答

1条回答 默认 最新

  • douzhongjian0752 2018-07-09 11:07
    关注

    Updating answer based on the changes to your question. The endless library can allow you to handle that signal by default. You will need to register a hook. I've expanded on your example code below:

    package main
    
    import (
        "os"
        "fmt"
        "syscall"
    
        "github.com/gin-gonic/gin"
        "github.com/fvbock/endless"
        "github.com/BurntSushi/toml"
    )
    
    type Config struct {
        Age  int
        Cats []string
    }
    
    var cfg Config
    
    func restart(c *gin.Context) {
        syscall.Kill(os.Getpid(), syscall.SIGUSR1)
    }
    
    func readConfig() {
        toml.DecodeFile("config.toml", &cfg)
        fmt.Println("Testing", cfg)
    }
    
    func main() {
            readConfig()
        router := gin.New()
    
        router.GET("/restart", restart)
    
        srv  := endless.NewServer("localhost:7777", router)
    
            srv.SignalHooks[endless.PRE_SIGNAL][syscall.SIGUSR1] = append(
                    srv.SignalHooks[endless.PRE_SIGNAL][syscall.SIGUSR1],
                    readConfig)
    
            if err := srv.ListenAndServe(); err != nil {
                    panic(err)
            }
    
    }
    

    Now when you call the restart endpoint, you should see the changes to config file refelcted in stdout. However in order to watch the file for changes you would need to use something like fsnotify

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真