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

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

报告相同问题?