GAE Golang - 网址抓取超时?(GAE Golang - urlfetch timeou

2019-08-02 13:11发布

我有网址抓取的在谷歌App Engine的Go的超时问题。 该应用程序似乎并不希望采取一个更长的超时比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秒钟后。 如何阻止它这样做? 我做出的一些错误在我的代码?

Answer 1:

您需要通过这样的持续时间(否则它会默认为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},
        },
    }


Answer 2:

试试下面的代码:

// 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)

礼貌@gosharplite



Answer 3:

综观围棋的应用程序引擎的源代码:

  • 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秒后超时。



Answer 4:

对我来说,这个工作:

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


Answer 5:

这是现在已经改变了与最近更新到库中。 现在,超时/延迟的时间必须由上下文进行, urlfetch.transport不再有它的时限字段。 context.WithTimeoutcontext.WithDeadline是使用的方法,这里是链接https://godoc.org/golang.org/x/net/context#WithTimeout



文章来源: GAE Golang - urlfetch timeout?