[英]Send a custom signal to curreng Golang process
我正在使用Go創建HTTP服務器。 每當我進行數據庫維護時,我都希望服務器將所有流量重定向到“當前正在進行維護”頁面。
當前,這是通過秘密管理頁面(例如http:// myhome / secret )完成的,但是我想知道是否可以使用信號-與TERM信號類似來完成此操作,但是可以暫時重定向而不是實際終止該過程。
例如。
/home/myhome> nohup startServer &
...
/home/myhome> changeMyServerStatus "maintenance"
我假設將有兩個可執行文件。“ startServer”和“ changeMyServerStatus”
因此,這類似於服務。 (如重新加載)但是,這可能嗎? 如果是這樣,您能給我一些提示嗎?
謝謝
如評論中所述,信號可能不是實現此目的的最佳方法。 我假設您仍然想要信號。
您可以使用標准用戶信號: 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)
})
}
您可以基於每個路由或直接將其應用到服務器的根處理程序 :
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
但是,手動操作nohup
和pkill
既繁瑣又容易出錯。 相反,請使用諸如systemd之類的服務管理器來管理您的流程。 Systemd允許您使用systemctl kill
發送任意信號:
systemctl kill -s SIGUSR1 myserver
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.