This article brings you relevant knowledge about Go. It mainly talks about how Go implements SSE and what needs to be paid attention to. Friends who are interested can take a look at it. I hope it will be helpful to you. Everyone is helpful.
1. Server code
package main import ( "fmt" "net/http" "time" ) type SSE struct { } func (sse *SSE) ServeHTTP(rw http.ResponseWriter, req *http.Request) { flusher, ok := rw.(http.Flusher) if !ok { http.Error(rw, "Streaming unsupported!", http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "text/event-stream") rw.Header().Set("Cache-Control", "no-cache") rw.Header().Set("Connection", "keep-alive") rw.Header().Set("Access-Control-Allow-Origin", "*") for { select { case <-req.Context().Done(): fmt.Println("req done...") return case <-time.After(500 * time.Millisecond): // 返回数据包含id、event(非必须)、data,结尾必须使用\n\n fmt.Fprintf(rw, "id: %d\nevent: ping \ndata: %d\n\n", time.Now().Unix(), time.Now().Unix()) flusher.Flush() } } } func SendData(data chan int64) chan int64 { for { data <- time.Now().Unix() time.Sleep(time.Second * time.Duration(2)) } } func main() { http.Handle("/sse", &SSE{}) http.ListenAndServe(":8080", nil) }
2. Client code
const source = new EventSource('http://127.0.0.1:8080/sse'); source.onopen = () => { console.log('链接成功'); }; source.addEventListener("ping",function(res){ console.log('获得数据:' + res.data); }) source.onerror = (err) => { console.log(err); };
3. Notes (Important)
If the server provides event
parameters (the complete message includes id, data, event), then the client needs Use addEventListener
to explicitly listen to this event, so that the message can be obtained normally, otherwise the event will not be triggered. If the server does not provide event
parameters, only id, data
, etc., you can use the onmessage
callback to listen for messages:
Scenario 1: The server has event
parameters, and defines a specific event called ping
const source = new EventSource('http://127.0.0.1:8080/sse'); source.onopen = () => { console.log('链接成功'); }; source.addEventListener("ping",function(res){ console.log('获得的数据是:' + res.data); }) source.onerror = (err) => { console.log(err); };
Scenario 2: The data returned by the server does not contain event
const source = new EventSource('http://127.0.0.1:8080/sse'); source.onopen = () => { console.log('链接成功'); }; source.onmessage(function(res){ console.log('获得的数据是:' + res.data); }) source.onerror = (err) => { console.log(err); };
[Recommended learning: go video tutorial]
The above is the detailed content of Let's talk about how to implement SSE in Go? What should I pay attention to?. For more information, please follow other related articles on the PHP Chinese website!