http - 向当前 Golang 进程发送自定义信号

标签 http go server signals reload

我正在使用 Go 创建一个 HTTP 服务器。每当我进行数据库维护时,我都希望服务器将所有流量重定向到“当前正在维护”页面。

目前,这是由 secret 管理页面(例如 http://myhome/secret)完成的,但我想知道这是否可以通过信号来完成 - 类似于 TERM 信号,但暂时重定向而不是实际终止进程。

例如。

/home/myhome> nohup startServer &
... 
/home/myhome> changeMyServerStatus "maintenance"

我假设会有两个可执行文件..“startServer”和“changeMyServerStatus”

因此,这类似于服务。 (比如重新加载)但是,这可能吗?如果是这样,你能给我一些提示吗?

谢谢

最佳答案

如评论中所述,信号可能不是实现此目的的最佳方式。尽管如此,我假设您确实需要信号。

您可以使用 standard用户信号:SIGUSR1 启用维护,SIGUSR2 禁用它。

使用os/signal获得这些信号的通知并更新程序状态:

// Brief example code. Real code might be structured differently
// (perhaps pack up maint and http.Server in one type MyServer).

var maint uint32 // atomic: 1 if in maintenance mode

func handleMaintSignals() {
    ch := make(chan os.Signal, 1)
    go func() { // FIXME: use Server.RegisterOnShutdown to terminate this
        for sig := range ch {
            switch sig { // FIXME: add logging
            case syscall.SIGUSR1:
                atomic.StoreUint32(&maint, 1)
            case syscall.SIGUSR2:
                atomic.StoreUint32(&maint, 0)
            }
        }
    }()
    signal.Notify(ch, syscall.SIGUSR1, syscall.SIGUSR2)
}

让中间件查看该状态并做出相应响应:

func withMaint(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if atomic.LoadUint32(&maint) == 1 {
            http.Error(w, "Down for maintenance", http.StatusServiceUnavailable)
            return
        }
        next.ServeHTTP(w, r)
    })
}

您可以在每个路由的基础上应用此中间件,或直接应用到服务器的 root handler :

func main() {
    handleMaintSignals()
    srv := http.Server{
        Addr:    ":17990",
        Handler: withMaint(http.DefaultServeMux),
    }
    srv.ListenAndServe()
}

您不需要像 changeMyServerStatus 这样的第二个可执行文件。使用操作系统的工具发送信号,例如 pkill :

$ nohup myserver &

$ curl http://localhost:17990/
404 page not found

$ pkill -USR1 myserver

$ curl http://localhost:17990/
Down for maintenance

$ pkill -USR2 myserver

$ curl http://localhost:17990/
404 page not found

但是手动兼顾 nohuppkill 既乏味又容易出错。相反,请使用服务管理器,例如 systemd管理您的流程。 Systemd 允许您使用 systemctl kill 发送任意信号:

systemctl kill -s SIGUSR1 myserver

关于http - 向当前 Golang 进程发送自定义信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995494/

相关文章:

python - 使用python从windows主机访问虚拟机MySQL数据库

server - cpanel托管中的laravel服务器错误500

android - 通过 no-ip 使用 HTTP POST/PUT 的问题

php - Laravel 将 Http 重定向到 Https

go - 包的类型不能用作 vendor 包的类型

excel - Go中未提供工作表/节名称时如何从XLS文件读取所有行

javascript - 客户端(JS-Browser)和服务器(PHP)通过 Web-Socket 通过 IP 进行通信

java - 需要注销时基本身份验证的替代方案?

Go 中的递归

apache - 如何杀死 apache(老一代)进程