在我的代码中,我os.Interrupt在关闭之前收听了以下内容package mainimport ( "net/http" "os" "os/signal" "syscall")var passer *DataPasserconst maxClients = 1func init() { passer = &DataPasser{ data: make(chan sseData), logs: make(chan string), connection: make(chan struct{}, maxClients), }}func main() { http.HandleFunc("/sse", passer.HandleSignal) go http.ListenAndServe(":1234", nil) // Listen to Ctrl+C (you can also do something else that prevents the program from exiting) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) <-c if client.IsConnected() { client.Disconnect() }}这passer.HandleSignal是一个将 SSE 发送Server Sent Event到客户端的函数,如下所示:package mainimport ( "fmt" "net/http")type sseData struct { event, message string}type DataPasser struct { data chan sseData connection chan struct{} // To control maximum allowed clients connections}func (p *DataPasser) HandleSignal(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") fmt.Println("Client connected from IP:", r.RemoteAddr) p.connection <- struct{}{} flusher, ok := w.(http.Flusher) if !ok { http.Error(w, "Internal error", 500) return } fmt.Fprint(w, "event: notification\ndata: Connection to WhatsApp server ...\n\n") flusher.Flush() // Connect to the WhatsApp client go Connect() for { select { case data := <-p.data: fmt.Println("recieved") 我的问题是,如果用户使用 Ctrl+C 中断了应用程序,该main函数正在响应它,我需要它向它发送数据,parser以便处理程序向客户端发送服务器已关闭的通知
1 回答
HUX布斯
TA贡献1876条经验 获得超6个赞
我找到了解决方案,它很简单,只需将日期传递给parser在 os.interupt 范围内定义为全局变量的对象,如下所示:
<-c
if client.IsConnected() {
passer.data <- sseData{
event: "notification",
message: "Server is shut down at the host machine...",
}
client.Disconnect()
}
- 1 回答
- 0 关注
- 76 浏览
添加回答
举报
0/150
提交
取消