英文:
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('\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()
答案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 := &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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论