Go实现SSE的方式和需要注意的事项

一、服务端代码

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

二、客户端代码

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

三、注意事项(重要)

如果服务器端提供了event参数(完整的消息包含id、data、event),那么客户端就需要使用addEventListener 显式监听这个事件,才会正常获取消息,否则事件不会触发。如果服务器端没有提供event 参数,只有id、data等,可以使用onmessage回调监听消息:

  • 场景一:服务器有event 参数,并且定义了一个叫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);
    };
  • 场景二:服务器返回的数据不包含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);
      };
本作品采用《CC 协议》,转载必须注明作者和本文链接
失色天空
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!