The*_*chu 4 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
}
Run Code Online (Sandbox Code Playgroud)
无论我尝试设置什么TimeoutDuration,该应用程序在大约5秒后超时.怎么阻止它这样做?我的代码中有错误吗?
orc*_*man 13
您需要像这样传递持续时间(否则它将默认为5秒超时):
tr := &urlfetch.Transport{Context: c, Deadline: time.Duration(30) * time.Second}
Run Code Online (Sandbox Code Playgroud)
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},
},
}
Run Code Online (Sandbox Code Playgroud)