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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?