GAE Golang - urlfetch 超时?

4

我在使用 Go 语言的 Google App Engine 进行 urlfetch 时遇到了超时问题。似乎应用程序不愿意设置更长的超时时间(它会忽略较长的超时时间并在自己的时间后超时)。

我的代码如下:

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秒钟后都会超时。如何防止这种情况发生?我的代码是否有错误?
5个回答

13
你需要这样传递时间长度(否则它将默认为5秒超时时间):

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

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

2016年1月2日更新:

随着新的GAE Go语言包(google.golang.org/appengine/*)的推出,这个问题已经改变了。在传输过程中,urlfetch不再接收截止时间参数。

你现在应该通过新的context包来设置超时时间。例如,以下是如何设置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},
        },
    }

你不需要像那样转换常量,最好使用30 * time.Second - Dave C

3

尝试以下代码:

// 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,
        },
    }
}

这是如何使用它的方法。
// urlfetch
client := createClient(c, time.Second*60)

Courtesy @gosharplite


2

对我来说,这个方法有效:

ctx_with_deadline, _ := context.WithTimeout(ctx, 15*time.Second)
client := urlfetch.Client(ctx_with_deadline)

2

1

最近对该库进行的更新已经改变了这种情况。现在超时/延迟的持续时间必须由上下文进行传递,urlfetch.transport不再具有其中的截止日期字段。要使用context.WithTimeoutcontext.WithDeadline方法,请参见此链接https://godoc.org/golang.org/x/net/context#WithTimeout


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接