维持活动请求的连续提供
时间:2024-03-26
浏览:191
作者:佚名
本文讨论了将 Node.js 中保持活动的 HTTP 请求转换为 Go 代码的解决方案。Node.js 代码使用 data 事件处理程序来处理部分更新,而 Go 代码使用 ioutil.ReadAll(),这会导致阻塞,因为 CouchDB 保持连接打开状态。解决方案是使用 resp.body.read() 等方法处理部分更新缓冲区,从而允许在连接关闭之前接收部分更新。
我正在尝试将下面的nodejs代码转换为go。我必须向 pouchdb 服务器的 _changes?feed=continuous 建立保持活动的 http 请求。但是,我无法在 go 中实现它。
var http = require('http')
var agent = new http.agent({
keepalive: true
});
var options = {
host: 'localhost',
port: '3030',
method: 'get',
path: '/downloads/_changes?feed=continuous&include_docs=true',
agent
};
var req = http.request(options, function(response) {
response.on('data', function(data) {
let val = data.tostring()
if(val == '\n')
console.log('newline')
else {
console.log(json.parse(val))
//to close the connection
//agent.destroy()
}
});
response.on('end', function() {
// data received completely.
console.log('end');
});
response.on('error', function(err) {
console.log(err)
})
});
req.end();
下面是go代码
client := &http.Client{}
data := url.Values{}
req, err := http.NewRequest("GET", "http://localhost:3030/downloads/_changes?feed=continuous&include_docs=true", strings.NewReader(data.Encode()))
req.Header.Set("Connection", "keep-alive")
resp, err := client.Do(req)
fmt.Println(resp.Status)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
我收到状态 200 好的,但没有打印任何数据,它卡住了。另一方面,如果我使用 longpoll 选项,即。 http://localhost:3030/downloads/_changes?feed=longpoll 然后我正在接收数据。
解决方案
终于,我解决了这个问题。该问题与 disablecompression 标志有关。 https://github.com/golang/go/issues/16488这个问题给了我一些提示。
通过设置 disablecompression: true 解决了该问题。
client := &http.client{传输: &http.transport{
禁用压缩:true,
}}
我假设 client := &http.client{} 发送 disablecompression : false 默认情况下,pouchdb 服务器发送压缩的 json,因此收到的数据被压缩,resp.body.read 无法读取。
您的代码“按预期”运行,并且您在 go 中编写的内容与 node.js 中显示的代码不同。 go 代码会阻塞 ioutil.readall(resp.body),因为 couchdb 服务器保持连接打开状态。一旦服务器关闭连接,您的客户端代码将打印出 result,因为 ioutil.readall() 将能够读取直到 eof 的所有数据。
来自CouchDB documentation关于连续进给:
您可以尝试实验,将 &timeout=1 添加到 url,这将强制 couchdb 在 1 秒后关闭连接。然后,您的 go 代码应该打印整个响应。
node.js 代码的工作方式不同,每次服务器发送一些数据时都会调用事件 data 处理程序。如果您想实现相同的目标并在部分更新到来时(在连接关闭之前)处理部分更新,则不能使用 ioutil.ReadAll(),因为它等待 eof(因此在您的情况下会阻塞),但像 resp.body.read() 之类的东西可以处理部分更新缓冲区。这是非常简化的代码片段,它演示了这一点,并且应该为您提供基本的想法:
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
)
func main() {
client := &http.Client{}
data := url.Values{}
req, err := http.NewRequest("GET", "http://localhost:3030/downloads/_changes?feed=continuous&include_docs=true", strings.NewReader(data.Encode()))
req.Header.Set("Connection", "keep-alive")
resp, err := client.Do(req)
defer resp.Body.Close()
fmt.Println(resp.Status)
if err != nil {
fmt.Println(err)
}
buf := make([]byte, 1024)
for {
l, err := resp.Body.Read(buf)
if l == 0 && err != nil {
break // this is super simplified
}
// here you can send off data to e.g. channel or start
// handler goroutine...
fmt.Printf("%s", buf[:l])
}
fmt.Println()
}
在现实世界的应用程序中,您可能希望确保 buf 保存看起来像有效消息的内容,然后将其传递到通道或处理程序 goroutine 进行进一步处理。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《维持活动请求的连续提供》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
