From 0d71f2936f56bdb87c8725d5ad9f6dec0daa56c1 Mon Sep 17 00:00:00 2001 From: Rizhiy Olexandr Date: Mon, 7 May 2018 21:46:55 +0300 Subject: [PATCH] add rate limits to error wrapper (#39) --- models/pinterest_error.go | 2 ++ models/rate_limit.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 models/rate_limit.go diff --git a/models/pinterest_error.go b/models/pinterest_error.go index 2f7b35d..dc472f5 100644 --- a/models/pinterest_error.go +++ b/models/pinterest_error.go @@ -12,6 +12,7 @@ import ( type PinterestError struct { StatusCode int `json:"status_code"` Message string `json:"message"` + Limit TypeRatelimit } func (e *PinterestError) Error() string { @@ -32,6 +33,7 @@ func WrapPinterestError(httpResponse *http.Response, bodyResponse *Response, err return &PinterestError{ StatusCode: httpResponse.StatusCode, Message: bodyResponse.Message, + Limit: GetRatelimit(httpResponse), } } diff --git a/models/rate_limit.go b/models/rate_limit.go new file mode 100644 index 0000000..d35f4e6 --- /dev/null +++ b/models/rate_limit.go @@ -0,0 +1,33 @@ +package models + +import ( + "net/http" + "strconv" + "fmt" +) + +type TypeRatelimit struct { + Remaining int + Limit int + Refresh int +} + +func GetLimit(httpResp *http.Response, key string) int { + if val, ok := httpResp.Header[key]; ok { + rateLimit, err := strconv.Atoi(val[0]) + if err == nil { + fmt.Println(err) + return 0 + } + return rateLimit + } + return 0 +} + +func GetRatelimit(httpResp *http.Response) TypeRatelimit { + return TypeRatelimit { + Remaining: GetLimit(httpResp, "X-Ratelimit-Refresh"), + Limit: GetLimit(httpResp, "X-Ratelimit-Limit"), + Refresh: GetLimit(httpResp, "X-Ratelimit-Remaining"), + } +} \ No newline at end of file