OStack程序员社区-中国程序员成长平台

标题: google-app-engine - GAE Golang - urlfetch 超时? [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-16 06:38
标题: google-app-engine - GAE Golang - urlfetch 超时?

我在 Go 中的 Google App Engine 上遇到 urlfetch 超时的问题。该应用程序似乎不希望超过大约 5 秒的超时时间(它会忽略更长的超时时间并在其自己的时间之后超时)。

我的代码是:

var TimeoutDuration time.Duration = time.Second*30

func Call(c appengine.Context, address string, allowInvalidServerCertificate bool, method string, id interface{}, params []interface{})(map[string]interface{}, error){
    data, err := json.Marshal(map[string]interface{}{
        "method": method,
        "id":     id,
        "params": params,
    })
    if err != nil {
        return nil, err
    }

    req, err:=http.NewRequest("OST", address, strings.NewReader(string(data)))
    if err!=nil{
        return nil, err
    }

    tr := &urlfetch.Transport{Context: c, Deadline: TimeoutDuration, AllowInvalidServerCertificate: allowInvalidServerCertificate}

    resp, err:=tr.RoundTrip(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    result := make(map[string]interface{})
    err = json.Unmarshal(body, &result)
    if err != nil {
        return nil, err
    }
    return result, nil
}

无论我如何设置 TimeoutDuration到,应用程序在大约 5 秒后超时。如何防止它这样做?我在我的代码中犯了一些错误吗?



Best Answer-推荐答案


您需要像这样传递持续时间(否则将默认为 5 秒超时):

tr := &urlfetch.Transport{Context: c, Deadline: time.Duration(30) * time.Second}

2016 年 1 月 2 日更新:

使用新的 GAE golang 包 ( google.golang.org/appengine/* ),情况发生了变化。 urlfetch不再在传输中接收截止时间持续时间。

您现在应该通过新的上下文包设置超时。例如,这是您设置 1 分钟截止时间的方式:
func someFunc(ctx context.Context) {
    ctx_with_deadline, _ := context.WithTimeout(ctx, 1*time.Minute)
    client := &http.Client{
        Transport: &oauth2.Transport{
            Base:   &urlfetch.Transport{Context: ctx_with_deadline},
        },
    }

关于google-app-engine - GAE Golang - urlfetch 超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317472/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4