我在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秒后超时。如何防止它这样做?我在代码中犯了什么错误吗?
发布于 2014-10-21 02:24:18
您需要像这样传递时长(否则将默认为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},
},
}发布于 2015-03-13 18:11:24
尝试下面的代码:
// 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
发布于 2012-11-16 02:53:26
看一下Go的appengine的源代码:
和protobuffer生成的代码:
看起来持续时间本身不应该有问题。
我的猜测是appengine内部的整个应用程序在5秒后超时。
https://stackoverflow.com/questions/13317472
复制相似问题