我想把下面的nodejs代码转换为Go。我必须建立保持活着的http请求到PouchDB服务器的_changes?feed=continuous。然而,我无法在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 OK,但没有数据被打印出来,它卡住了。另一方面,如果我使用longpoll选项,即。http:/localhost:3030downloads_changes?feed=longpoll。 然后我接收数据。
你的代码是 "按照预期 "工作的,你在Go中写的代码和Node.js中显示的代码是不一样的。Go代码块上 ioutil.ReadAll(resp.Body)
因为连接是由CouchDB服务器保持打开的。一旦服务器关闭了连接,你的客户端代码将打印出以下信息 result
作为 ioutil.ReadAll()
将能够读取所有数据到EOF。
从 CouchDB文档 关于连续馈送。
连续feed保持开放并连接到数据库,直到明确关闭,并且在变化发生时,即以近乎实时的方式将其发送到客户端。与longpoll feed类型一样,你可以设置超时和心跳间隔,以确保连接保持开放,以接收新的变化和更新。
您可以尝试实验并添加 &timeout=1
到URL,这将迫使CouchDB在1s后关闭连接。然后你的Go代码应该打印整个响应。
Node.js代码的工作原理不同,event 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进行进一步处理。
最后,我终于能够解决这个问题。这个问题与 DisableCompression
标志。https:/github.comgolanggoissues16488。 这个问题给了我一些提示。
通过设置 DisableCompression: true
解决了这个问题。client := &http.Client{Transport: &http.Transport{
DisableCompression: true,
}}
我假设 client := &http.Client{}
发送 DisableCompression : false
默认情况下,pouchdb服务器发送的是压缩的json,因此收到的数据被压缩,resp.Body.Read无法读取。