search
HomeBackend DevelopmentGolangLet'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.

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)
}

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);
    };

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);
};

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);
  };

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

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
go语言有没有缩进go语言有没有缩进Dec 01, 2022 pm 06:54 PM

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

Spring Boot怎么使用SSE方式向前端推送数据Spring Boot怎么使用SSE方式向前端推送数据May 10, 2023 pm 05:31 PM

前言SSE简单的来说就是服务器主动向前端推送数据的一种技术,它是单向的,也就是说前端是不能向服务器发送数据的。SSE适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用SpringBoot来实现一个简单的模拟向前端推动进度数据,前端页面接受后展示进度条。服务端在SpringBoot中使用时需要注意,最好使用SpringWeb提供的SseEmitter这个类来进行操作,我在刚开始时使用网上说的将Content-Type设置为text-stream这种方式发现每次前端每次都会重新创建接。最

SSE 与 WebSocketSSE 与 WebSocketApr 17, 2024 pm 02:18 PM

在本文中,我们将比较服务器发送事件(SSE)和 WebSocket,两者都是用于传递数据的可靠方法。我们将在八个方面对它们进行分析,包括通信方向、底层协议、安全、易用性、性能、消息结构、易用性和测试工具。这些方面的比较总结如下:类别服务器发送事件 (SSE)WebSocket通信方向单向双向底层协议HTTPWebSocket 协议安全与 HTTP 相同存在安全漏洞易用性设置简单设置复杂性能消息发送速度快受消息处理和连接管理影响消息结构纯文本文本或二进制易用性广泛可用对 WebSocket 集成有

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

tidb是go语言么tidb是go语言么Dec 02, 2022 pm 06:24 PM

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言能不能编译go语言能不能编译Dec 09, 2022 pm 06:20 PM

go语言能编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言。对Go语言程序进行编译的命令有两种:1、“go build”命令,可以将Go语言程序代码编译成二进制的可执行文件,但该二进制文件需要手动运行;2、“go run”命令,会在编译后直接运行Go语言程序,编译过程中会产生一个临时文件,但不会生成可执行文件。

【整理分享】一些GO面试题(附答案解析)【整理分享】一些GO面试题(附答案解析)Oct 25, 2022 am 10:45 AM

本篇文章给大家整理分享一些GO面试题集锦快答,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)