如何在收到 os.Interrupt后从服务器向客户端发送信号

在我的代码中,我os.Interrupt在关闭之前收听了以下内容


package main


import (

    "net/http"

    "os"

    "os/signal"

    "syscall"

)


var passer *DataPasser


const maxClients = 1


func 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 main


import (

    "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以便处理程序向客户端发送服务器已关闭的通知


沧海一幻觉
浏览 82回答 1
1回答

HUX布斯

我找到了解决方案,它很简单,只需将日期传递给parser在 os.interupt 范围内定义为全局变量的对象,如下所示:&nbsp; &nbsp; <-c&nbsp; &nbsp; if client.IsConnected() {&nbsp; &nbsp; &nbsp; &nbsp; passer.data <- sseData{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event:&nbsp; &nbsp;"notification",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: "Server is shut down at the host machine...",&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; client.Disconnect()&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go