From 9791e4bee05ad0f7bafa1eb21e56a1c16a29a504 Mon Sep 17 00:00:00 2001 From: Robbie Trencheny Date: Mon, 25 Dec 2017 21:51:16 -0500 Subject: [PATCH] Add rate limit support --- result.go | 23 +++++++++++++++++++++++ session.go | 14 ++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/result.go b/result.go index 874243e..2b65777 100644 --- a/result.go +++ b/result.go @@ -82,6 +82,20 @@ type DebugInfo struct { FacebookRev string // the x-fb-rev HTTP header. } +// UsageInfo is the app usage (rate limit) information returned by facebook when rate limits are possible. +type UsageInfo struct { + App struct { + CallCount int `json:"call_count"` + TotalTime int `json:"total_time"` + TotalCPUTime int `json:"total_cputime"` + } `json:"app"` + Page struct { + CallCount int `json:"call_count"` + TotalTime int `json:"total_time"` + TotalCPUTime int `json:"total_cputime"` + } `json:"page"` +} + // DebugMessage is one debug message in "__debug__" of graph API response. type DebugMessage struct { Type string @@ -433,6 +447,15 @@ func (res Result) DebugInfo() *DebugInfo { return debugInfo } +// UsageInfo returns app and page usage info (rate limits) +func (res Result) UsageInfo() *UsageInfo { + if usageInfo, ok := res["__usage__"]; ok { + ui := usageInfo.(UsageInfo) + return &ui + } + return nil +} + func (res Result) decode(v reflect.Value, fullName string) error { for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { v = v.Elem() diff --git a/session.go b/session.go index 4cfea16..aef2e1f 100644 --- a/session.go +++ b/session.go @@ -143,6 +143,7 @@ func (session *Session) Request(request *http.Request) (res Result, err error) { res, err = MakeResult(data) session.addDebugInfo(res, response) + session.addUsageInfo(res, response) if res != nil { err = res.Err() @@ -347,6 +348,7 @@ func (session *Session) graph(path string, method Method, params Params) (res Re var response *http.Response response, err = session.sendPostRequest(graphUrl, params, &res) session.addDebugInfo(res, response) + session.addUsageInfo(res, response) if res != nil { err = res.Err() @@ -561,6 +563,18 @@ func (session *Session) addDebugInfo(res Result, response *http.Response) Result return res } +func (session *Session) addUsageInfo(res Result, response *http.Response) Result { + var usageInfo UsageInfo + if response.Header.Get("X-App-Usage") != "" { + json.Unmarshal([]byte(response.Header.Get("X-App-Usage")), &usageInfo.App) + } + if response.Header.Get("X-Page-Usage") != "" { + json.Unmarshal([]byte(response.Header.Get("X-Page-Usage")), &usageInfo.Page) + } + res["__usage__"] = usageInfo + return res +} + // Context returns the session's context. // To change the context, use `Session#WithContext`. //