-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathusage.go
82 lines (72 loc) · 2.73 KB
/
usage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package gotwilio
import (
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
// These are the parameters to use when you are requesting account usage.
// See https://www.twilio.com/docs/usage/api/usage-record#read-multiple-usagerecord-resources
// for more info.
type UsageParameters struct {
Category string // Optional
StartDate string // Optional, in YYYY-MM-DD or as offset
EndDate string // Optional, in YYYY-MM-DD or as offset
IncludeSubaccounts bool // Optional
}
// UsageRecord specifies the usage for a particular usage category.
// See https://www.twilio.com/docs/usage/api/usage-record#usagerecord-properties
// for more info.
type UsageRecord struct {
AccountSid string `json:"account_sid"`
Category string `json:"category"`
Description string `json:"description"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
Price string `json:"price"`
PriceUnit string `json:"price_unit"`
Count int `json:"count,string"`
CountUnit string `json:"count_unit"`
Usage int `json:"usage,string"`
UsageUnit string `json:"usage_unit"`
AsOf string `json:"as_of"` // GMT timestamp formatted as YYYY-MM-DDTHH:MM:SS+00:00
// TODO: handle SubresourceUris
}
// UsageResponse contains information about account usage.
type UsageResponse struct {
PageSize int `json:"page_size"`
Page int `json:"page"`
UsageRecords []UsageRecord `json:"usage_records"`
}
func (twilio *Twilio) GetUsage(category, startDate, endDate string, includeSubaccounts bool) (*UsageResponse, *Exception, error) {
return twilio.GetUsageWithContext(context.Background(), category, startDate, endDate, includeSubaccounts)
}
func (twilio *Twilio) GetUsageWithContext(ctx context.Context, category, startDate, endDate string, includeSubaccounts bool) (*UsageResponse, *Exception, error) {
formValues := url.Values{}
formValues.Set("category", category)
formValues.Set("start_date", startDate)
formValues.Set("end_date", endDate)
formValues.Set("include_subaccounts", strconv.FormatBool(includeSubaccounts))
var usageResponse *UsageResponse
var exception *Exception
twilioUrl := twilio.BaseUrl + "/Accounts/" + twilio.AccountSid + "/Usage/Records.json"
res, err := twilio.get(ctx, twilioUrl+"?"+formValues.Encode())
if err != nil {
return nil, nil, err
}
defer res.Body.Close()
responseBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, nil, err
}
if res.StatusCode != http.StatusOK {
exception = new(Exception)
err = json.Unmarshal(responseBody, exception)
return nil, exception, err
}
usageResponse = new(UsageResponse)
err = json.Unmarshal(responseBody, usageResponse)
return usageResponse, nil, err
}