本篇文章给大家带来了关于go的相关知识,其中主要跟大家聊一聊go用什么方式实现sse,以及需要注意的事项,感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。
一、服务端代码
package mainimport (   "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);  };
【推荐学习:go视频教程】                                                
以上就是聊聊go怎么实现sse?需要注意什么?的详细内容。
   
 
   