在客户端上读取非缓冲的服务器推送事件。

huangapple go评论94阅读模式
英文:

Read not buffered Server-Sent Event on client

问题

我需要在我的 Golang 应用程序中读取 SSE,但返回的事件是缓冲的,而不是实时的。据我所见,这是由于标准的 Golang 传输机制造成的。我该如何修复这个问题,而不需要实现自己的传输机制?

这段代码受到 cryptix 解决方案的启发:

resp, _ := http.Get(sseURL)
events := make(chan Event)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
    event := Event{}
    reader := bufio.NewReader(resp.Body)

    for {
        line, err := reader.ReadBytes('\n')

        if err != nil {
            log.Println(os.Stderr, "error during resp.Body read:%s\n", err)
            close(events)
        }

        json.Unmarshal(line, &event)

        events <- event
    }
    wg.Done()
}()

go func() {
    for ev := range events {
        log.Println(ev)
    }
}()
wg.Wait()
英文:

I need to read sse in my golang app, but instead of real-time, events return buffered. As I can see, this is because of standard golang transport. How can I fix this, without implementing my own transport?
This code is inspired by cryptix solution:

resp, _ := http.Get(sseURL)
events := make(chan Event)
wg:= sync.WaitGroup{}
wg.Add(1)
go func() {
	event:= Event{}
	reader := bufio.NewReader(resp.Body)

	for {
		line, err := reader.ReadBytes(&#39;\n&#39;)

		if err != nil {
			log.Println(os.Stderr, &quot;error during resp.Body read:%s\n&quot;, err)
			close(events)
		}

		json.Unmarshal(line,&amp;event)

		events&lt;-event
	}
	wg.Done()
}()

go func(){
	for ev:= range events {
		log.Println(ev)
	}
}()
wg.Wait()

答案1

得分: 2

我明白了,数据被nginx缓冲了,这是由于透明压缩导致的。所以,为了立即获取数据,我们必须禁用压缩,像这样:

client := &http.Client{}
transport := &http.Transport{}
transport.DisableCompression = true
client.Transport = transport
req, err := http.NewRequest("GET", essURL, nil)
if err != nil {
    log.Fatal(err)
}
resp, _ := client.Do(req)

reader := bufio.NewReader(resp.Body)
for {
    line, _ := reader.ReadSlice('\n')
    log.Println(string(line))
}
英文:

I figured out, data was buffered by nginx, because of transparent compression. So, to get data without delay we must disable compression like this:

client := &amp;http.Client{}
transport := &amp;http.Transport{}
transport.DisableCompression = true
client.Transport = transport
req, err := http.NewRequest(&quot;GET&quot;, essURL, nil)
if err != nil {
	log.Fatal(err);
}
resp, _ := client.Do(req)

reader := bufio.NewReader(resp.Body)
for {
	line,_:=reader.ReadSlice(&#39;\n&#39;)
	log.Println(string(line))		
}

huangapple
  • 本文由 发表于 2015年9月29日 20:33:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/32844142.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定