Google App Engine Go HTTP请求到一个慢速页面

huangapple go评论85阅读模式
英文:

Google App Engine Go HTTP request to a slow page

问题

我想在Google App Engine中使用Go语言发起一个HTTP请求,访问一个响应较慢的网站。我的代码如下:

func request(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    client := urlfetch.Client(c)
    resp, err := client.Get("http://www.example.com")
    if err != nil {
        log.Print("err %s", err.String())
        return
    }
    ...
}

在调用我的网站后,我得到了如下错误:

API error 1 (urlfetch: INVALID_URL): ApplicationError: 5 timed out

经过一些调查,我发现了一些关于Transport类的参考资料,它允许等待HTTP请求的时间长达60秒,但我找不到任何关于如何使用它的描述或示例。

我该如何在GAE Go中发起一个超过5秒的HTTP请求?

英文:

I want to make a HTTP request using Google App Engine in Go to a slow-responding website. My code is:

func request(w http.ResponseWriter, r *http.Request) {
	c:=appengine.NewContext(r)
    client := urlfetch.Client(c)
    resp, err := client.Get("http://www.example.com")
    if err != nil {
		log.Print("err %s", err.String())
        return
    }
    ...}

After calling my website, I get such an error:

API error 1 (urlfetch: INVALID_URL): ApplicationError: 5 timed out

After looking a bi into it, I found some reference to Transport class that allows to wait for HTTP requests for up to 60 seconds, but I can't find any description or example on how to make that work.

How can I make a HTTP request in GAE Go that will have a deadline longer than 5 seconds?

答案1

得分: 5

我建议如果可能的话,使用任务队列 API在主请求处理程序之外进行 urlfetch。

在构建 urlfetch.Transport 时,你应该能够像这样覆盖默认的截止时间:

t := urlfetch.Transport{Context:c, DeadlineSeconds: 5.0}
client := http.Client{Transport: &t}
英文:

I would recommend if possible, doing the urlfetch outside of your main request handler using Tasks Queue API.

When constructing urlfetch.Transport, you should be able to override the default deadline like this:

t := urlfetch.Transport{Context:c, DeadlineSeconds: 5.0}
client := http.Client{Transport: &t}

答案2

得分: 0

远程站点有时因为DNS解析而变慢。使用IP地址可能会有帮助(在连接到http://a.b.c.d之前解析目标主机)。

我不知道Go是否允许您定义更长的超时值 - 您可以多次轮询,直到收到回复(或达到重试次数)。

无论如何,祝您好运。

英文:

Remote sites are sometimes slow because of DNS resolution. Using the IP address might help (resolve the target host before connecting to http://a.b.c.d).

I don't know if Go lets you define a longer timeout value - what you can do is to poll several times until you get a reply (or have expired your retries count).

Good luck anyway.

huangapple
  • 本文由 发表于 2011年10月29日 22:48:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/7939614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定