保持对 _change 连续馈送的请求

Keep alive request for _change continuous feed

我正在尝试将以下 nodejs 代码转换为 Go。我必须建立对 PouchDB 服务器的 _changes?feed=continuous 的 keep alive 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那我正在接收数据。

您的代码可以正常工作 "as expected",并且您在 Go 中编写的内容与 Node.js 中显示的代码不同。在 ioutil.ReadAll(resp.Body) 上执行代码块,因为 CouchDB 服务器保持连接打开。服务器关闭连接后,您的客户端代码将打印出 result,因为 ioutil.ReadAll() 将能够读取所有数据直至 EOF。

来自CouchDB documentation关于连续进纸:

A continuous feed stays open and connected to the database until explicitly closed and changes are sent to the client as they happen, i.e. in near real-time. As with the longpoll feed type you can set both the timeout and heartbeat intervals to ensure that the connection is kept open for new changes and updates.

您可以尝试将 &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 以进行进一步处理。

终于,我解决了这个问题。该问题与 DisableCompression 标志有关。 https://github.com/golang/go/issues/16488 这个问题给了我一些提示。

通过设置 DisableCompression: true 解决了这个问题。
client := &http.Client{Transport: &http.Transport{ DisableCompression: true, }}

我假设 client := &http.Client{} 默认发送 DisableCompression : false 并且 pouchdb 服务器正在发送压缩的 json,因此接收到的数据被压缩并且 resp.Body.Read 无法读取。