


Let's talk about how to implement SSE in Go? What should I pay attention to?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...
