首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GAE Golang - urlfetch超时?

GAE Golang - urlfetch超时?
EN

Stack Overflow用户
提问于 2012-11-10 07:22:41
回答 5查看 3.4K关注 0票数 4

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

我的代码是:

代码语言:javascript
复制
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("POST", 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秒后超时。如何防止它这样做?我在代码中犯了什么错误吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2014-10-21 02:24:18

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

代码语言:javascript
复制
tr := &urlfetch.Transport{Context: c, Deadline: time.Duration(30) * time.Second}

2016年1月2日更新:

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

现在,您应该通过新的上下文包设置超时。例如,您可以这样设置1分钟的截止时间:

代码语言:javascript
复制
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},
        },
    }
票数 13
EN

Stack Overflow用户

发布于 2015-03-13 18:11:24

尝试下面的代码:

代码语言:javascript
复制
// createClient is urlfetch.Client with Deadline
func createClient(context appengine.Context, t time.Duration) *http.Client {
    return &http.Client{
        Transport: &urlfetch.Transport{
            Context:  context,
            Deadline: t,
        },
    }
}

下面是如何使用它。

代码语言:javascript
复制
// urlfetch
client := createClient(c, time.Second*60)

礼貌@gosharplite

票数 3
EN

Stack Overflow用户

发布于 2012-11-16 02:53:26

看一下Go的appengine的源代码:

  • http://code.google.com/p/appengine-go/source/browse/appengine/urlfetch/urlfetch.go

和protobuffer生成的代码:

  • http://code.google.com/p/appengine-go/source/browse/appengine_internal/urlfetch/urlfetch_service.pb.go

看起来持续时间本身不应该有问题。

我的猜测是appengine内部的整个应用程序在5秒后超时。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13317472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档