我正在尝试在Google App Engine中的Golang中创建Reddit API。我的代码:
package RedditAPI
import(
"appengine"
"encoding/json"
"io/ioutil"
"net/http"
"appengine/urlfetch"
"time"
"net/url"
)
func GetTopSubmissions(c appengine.Context){
one, two:=Call(c, "http://www.reddit.com/r/Bitcoin/top.json", "POST", nil);
c.Infof("%v, %v", one, two);
}
func Call(c appengine.Context, address string, requestType string, values url.Values)(map[string]interface{}, error){
req, err:=http.NewRequest("GET", address, nil)
if err!=nil{
c.Infof("Request: %v", err)
return nil, err
}
req.Header.Add("User-Agent", "This is a very creative name for a Reddit bot v1.0 by /u/username")
c.Infof("%v", req.Header.Get("User-Agent"))
c.Infof("%v", req)
c.Infof("%v", req.UserAgent())
duration, err:= time.ParseDuration("60s")
tr := &urlfetch.Transport{Context: c, Deadline: duration}
resp, err:=tr.RoundTrip(req)
if err != nil {
c.Infof("Post: %v", err)
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
c.Infof("ReadAll: %v", err)
return nil, err
}
result := make(map[string]interface{})
err = json.Unmarshal(body, &result)
if err != nil {
c.Infof("Unmarshal: %v", err)
c.Infof("%s", body)
return nil, err
}
return result, nil
}
退货
2013/05/23 03:00:34 Unsolicited response received on idle HTTP channel starting with "H"; err=<nil>
2013/05/23 03:01:42 INFO: &{GET http://www.reddit.com/r/Bitcoin/top.json HTTP/1.1 1 1 map[User-Agent:[This is a very creative name for a Reddit bot v1.0 by /u/username]] <nil> 0 [] false www.reddit.com map[] <nil> map[] <nil>}
2013/05/23 03:01:42 INFO: This is a very creative name for a Reddit bot v1.0 by /u/username
2013/05/23 03:01:42 INFO: map[error:429], <nil>
INFO 2013-05-23 03:01:42,720 server.py:584] default: "GET / HTTP/1.1" 200 81
造成此错误的原因是什么?
最佳答案
HTTP错误429是“请求太多”:http://tools.ietf.org/html/rfc6585#section-4
Reddit在https://github.com/reddit/reddit/wiki/API上说:“每分钟发出的请求不超过30个。这会使您的请求有些突发,但请保持头脑清醒。平均而言,我们每两秒钟收到的请求不应超过一个。”他们还说:“每30秒不要在同一页面上打过多次”。
如果您要为应用程序中的每个用户请求相同的资源,则可以使用GAE的内存缓存支持。如果您请求大量资源,则Reddit Wiki页面上会提及“一次请求多个资源”,因此可能存在一些用于批处理请求的功能(不确定,API并不熟悉)。如果您正在执行cronjob,则可以减少其运行频率。
无论如何,剩下的谜团更多是Reddit API问题,而不是Go问题。用(https://github.com/jzelinskie/reddit)注释的 repo matthewbauer或Reddit API文档可能还有更多。
关于api - Google App Engine Go-Reddit API返回错误429,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16711070/