Home > Backend Development > Golang > Let's talk about how to implement SSE in Go? What should I pay attention to?

Let's talk about how to implement SSE in Go? What should I pay attention to?

藏色散人
Release: 2023-02-24 19:42:50
forward
4922 people have browsed it

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.

Let's talk about how to implement SSE in Go? What should I pay attention to?

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)
}
Copy after login

2. Client code

    const source = new EventSource(&#39;http://127.0.0.1:8080/sse&#39;);
    source.onopen = () => {
        console.log(&#39;链接成功&#39;);
    };
    source.addEventListener("ping",function(res){
         console.log(&#39;获得数据:&#39; + res.data);
    })
    source.onerror = (err) => {
        console.log(err);
    };
Copy after login

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(&#39;http://127.0.0.1:8080/sse&#39;);
source.onopen = () => {
    console.log(&#39;链接成功&#39;);
};
source.addEventListener("ping",function(res){
     console.log(&#39;获得的数据是:&#39; + res.data);
})
source.onerror = (err) => {
    console.log(err);
};
Copy after login

Scenario 2: The data returned by the server does not contain event

const source = new EventSource(&#39;http://127.0.0.1:8080/sse&#39;);
  source.onopen = () => {
      console.log(&#39;链接成功&#39;);
  };
  source.onmessage(function(res){
       console.log(&#39;获得的数据是:&#39; + res.data);
  })
  source.onerror = (err) => {
      console.log(err);
  };
Copy after login

[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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template