gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:33:35 27 4
gpt4 key购买 nike

我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com