google-app-engine - GAE Golang - urlfetch 超时?

标签 google-app-engine timeout go 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("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 秒超时):

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/

相关文章:

超时 XMLHttpRequest

go - 两种不同语言之间的 Protocol Buffer

Heroku Go 应用崩溃

php - 使 App Engine for PHP 加载 BCMath 或 php.ini

jquery - 浏览器问题的多个打开选项卡的客户端脚本变量范围

python - Gae/cloudsql错误: Access denied for user 'root' @'cloudsqlproxy

xcode - 实际 iPad 上的 ASIHTTPRequest 错误,代码 2

google-app-engine - 意外的属性 static_dir :

python - Google App Engine Datastore 中是否可以有多值字段?

java - App Engine Java 高级查询类型