在我的代码中,我想执行以下操作:
从输入接收数据event
和message
根据接收到的数据格式化event
我想使用与 OOP 中的方法接近的东西,但看起来我搞砸了。
我写的是:
// Define the structs that contains the channels
type sseData struct {
event, message string
}
type DataPasser struct {
data chan sseData
logs chan string
connection chan struct{} // To control maximum allowed clients connections
}
// DEfine the struct's reciever that do the formating based on the input date
func (p *DataPasser) Format() {
data := <-p.data
switch {
case len(data.event) > 0:
p.logs <- fmt.Sprintf("event: %v\ndata: %v\n\n", data.event, data.message)
case len(data.event) == 0:
p.logs <- fmt.Sprintf("data: %v\n\n", data.message)
}
}
然后我有以下内容:
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")
setupCORS(&w, r)
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()
// Prepare dataParser `p` to recieve data through its sseData channel
go p.Format()
for {
select {
case c := <-p.logs:
fmt.Fprint(w, c)
flusher.Flush()
case <-r.Context().Done():
<-p.connection
fmt.Println("Connection closed")
return
}
}
}
FFIVE
慕虎7371278
相关分类