登录
首页 >  Golang >  Go问答

json.NewDecoder().Decode()可能忽略上下文截止日期

来源:stackoverflow

时间:2024-03-12 16:18:29 441浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《json.NewDecoder().Decode()可能忽略上下文截止日期》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我有一个 golang 程序,设置了上下文截止日期。我正在发送一个 http 请求,预计在阅读正文时会看到超出截止日期的错误。

似乎当我使用 ioutil.readall 读取响应正文时,该读取方法将被中断(?)并返回适当的错误(context.deadlineexceeded)。

但是,如果我使用 json.newdecoder(resp.body).decode 读取响应正文,则返回的错误为零(而不是 context.deadlineexceeded)。我的完整代码如下。这是 json.newdecoder(resp.body).decode 中的错误吗?

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

var url string = "http://ip.jsontest.com/"

func main() {
    readDoesntFail()
    readFails()
}

type IpResponse struct {
    Ip string
}

func readDoesntFail() {
    ctx, _ := context.WithTimeout(context.Background(), time.Second*5)

    req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    if err != nil {
        panic(err)
    }
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }

    ipResponse := new(IpResponse)
    time.Sleep(time.Second * 6)
    fmt.Println("before reading response body, context error is:", ctx.Err())
    err = json.NewDecoder(resp.Body).Decode(ipResponse)
    if err != nil {
        panic(err)
    }
    fmt.Println("Expected panic but there was none")
}

func readFails() {
    ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    if err != nil {
        panic(err)
    }
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }

    time.Sleep(time.Second * 6)
    fmt.Println("before reading response body, context error is:", ctx.Err())
    _, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("received expected error", err)
    }
}

正确答案


net/http 包可能使用缓冲区来处理请求。这意味着传入的响应正文可能会在您读取之前被部分或全部读取和缓冲,因此过期的上下文可能不会阻止您完成读取正文。这正是所发生的情况。

让我们修改您的示例以启动一个测试 http 服务器,该服务器故意延迟响应(部分):

ts := httptest.newserver(http.handlerfunc(func(w http.responsewriter, r *http.request) {
    s := []byte(`{"ip":"12.34.56.78"}`)
    w.write(s[:10])
    if f, ok := w.(http.flusher); ok {
        f.flush()
    }
    time.sleep(time.second * 6)
    w.write(s[10:])
}))
defer ts.close()
url = ts.url

readdoesntfail()
readfails()

此测试服务器发送与 ip.jsontest.com 响应类似的 json 对象。但它只发送 10 个字节的正文,然后刷新它,然后在发送其余部分之前故意休眠 6 秒,“允许”客户端超时。

现在让我们看看如果调用 readdoesntfail() 会发生什么:

before reading response body, context error is: context deadline exceeded
panic: Get "http://127.0.0.1:38230": context deadline exceeded

goroutine 1 [running]:
main.readDoesntFail()
    /tmp/sandbox721114198/prog.go:46 +0x2b4
main.main()
    /tmp/sandbox721114198/prog.go:28 +0x93

Go Playground 上尝试一下。

在您的示例中,json.decoder.decode() 读取已经缓冲的数据,因此过期的上下文在这里不起作用。在我的示例中 json.decoder.decode() 尝试从连接中读取数据,因为数据尚未缓冲(不可能,因为尚未发送),因此一旦上下文过期,进一步读取连接返回超出截止日期的错误。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>