-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
213 lines (175 loc) · 5.9 KB
/
client.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package appmetrica
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/valyala/fasthttp"
"golang.org/x/time/rate"
)
// Client binds HTTP API to simple function calls.
type Client struct {
apikey []byte
apikeyPost []byte
client *fasthttp.Client
limiters [3]rate.Limiter
}
func NewClient(token string) *Client {
c := new(Client)
c.SetAPIKey(token)
c.client = &fasthttp.Client{
Name: "appmetrica-go/0.0.0",
DialDualStack: true,
MaxConnsPerHost: 10,
MaxIdleConnDuration: 30 * time.Second,
ReadTimeout: 60 * time.Second,
MaxResponseBodySize: 0, // Unlimited response body.
}
return c
}
func (c *Client) Close() error {
return nil
}
// GetApplication возвращает информацию об указанном приложении.
func (c *Client) GetApplication(id int) (*Application, error) {
req, res := c.prepare()
uri := req.URI()
uri.SetPath(`/management/v1/application/` + strconv.Itoa(id))
var obj, err = c.do(req, res, nil)
return obj.Application, err
}
// ListApplications возвращает информацию о приложениях, доступных
// пользователю.
func (c *Client) ListApplications() ([]Application, error) {
req, res := c.prepare()
uri := req.URI()
uri.SetPath(`/management/v1/applications`)
var obj, err = c.do(req, res, nil)
return obj.Applications, err
}
// ModifyApplication добавляет приложение в AppMetrica.
func (c *Client) CreateApplication(name, tz string) (*Application, error) {
req, res := c.prepare()
req.Header.SetMethod("POST")
uri := req.URI()
uri.SetPath(`/management/v1/applications`)
var msg = Response{Application: &Application{Name: name, TimeZoneName: tz}}
var obj, err = c.do(req, res, msg)
return obj.Application, err
}
// ModifyApplication изменяет настройки приложения.
func (c *Client) ModifyApplication(id int, name, tz string) (*Application, error) {
req, res := c.prepare()
req.Header.SetMethod("PUT")
uri := req.URI()
uri.SetPath(`/management/v1/application/` + strconv.Itoa(id))
var msg = Response{Application: &Application{Name: name, TimeZoneName: tz}}
var obj, err = c.do(req, res, &msg)
return obj.Application, err
}
// DeleteApplication удаляет приложение.
func (c *Client) DeleteApplication(id int) error {
req, res := c.prepare()
req.Header.SetMethod("DELETE")
uri := req.URI()
uri.SetPath(`/management/v1/application/` + strconv.Itoa(id))
var _, err = c.do(req, res, nil)
return err
}
// ImportEvent загружает информацию о событии.
func (c *Client) ImportEvent(event ImportEvent) error {
return ErrNotImplemented
}
// ImportEvents загружает информацию о событиях. Функция в качестве аргумента
// принимает интерфейс Reader. Предполагается, что пользователь самостоятельно
// подготовил тело запроса в формате CSV, как того требует спецификация
// AppMetrica API. Задачу может упростить реализация интерфейса Reader тип
// EventImporter, который фильтрует и форматирует список событий.
func (c *Client) ImportEvents(reader io.Reader) error {
req, res := c.prepare()
req.Header.Del("Authorization")
req.Header.SetMethod("POST")
req.Header.SetContentType(`text/csv; charset=UTF-8`)
io.Copy(req.BodyWriter(), reader)
uri := req.URI()
uri.SetPath(`/logs/v1/import/events.csv`)
args := uri.QueryArgs()
args.SetBytesV(`post_api_key`, c.apikeyPost)
var _, err = c.do(req, res, nil)
return err
}
func (c *Client) SetAPIKey(token string) {
c.apikey = []byte(`OAuth ` + token)
}
func (c *Client) SetPostAPIKey(token string) {
c.apikeyPost = []byte(token)
}
func (c *Client) do(req *fasthttp.Request, res *fasthttp.Response, msg interface{}) (*Response, error) {
var err error
var obj Response
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(res)
// Encoder JSON message.
if msg != nil {
enc := json.NewEncoder(req.BodyWriter())
req.Header.SetContentType(`application/json; charset=UTF-8`)
if err = enc.Encode(msg); err != nil {
return &obj, err
}
}
// Print prepared request.
println("\033[1mRequest dump string\033[0m")
println(req.String())
// Make request.
if err = c.client.Do(req, res); err != nil {
return &obj, err
}
// Print received response.
println("\033[1mResponse dump string\033[0m")
println(res.String())
contentType := string(res.Header.Peek(`Content-Type`))
contentType = strings.Split(contentType, ";")[0]
switch contentType {
case "application/json", "application/x-yametrika+json":
return c.processJSON(res)
case "text/plain":
return c.processPlainText(res)
default:
var status = res.StatusCode()
var message = "unexpected content type: " + contentType
return &obj, NewError(status, message)
}
}
func (c *Client) processPlainText(res *fasthttp.Response) (*Response, error) {
if status := res.StatusCode(); status != http.StatusOK {
var message = string(res.Body())
return nil, NewError(status, message)
} else {
return nil, nil
}
}
func (c *Client) processJSON(res *fasthttp.Response) (*Response, error) {
var buf = bytes.NewBuffer(res.Body())
var dec = json.NewDecoder(buf)
var obj Response
if err := dec.Decode(&obj); err != nil {
return &obj, err
}
if obj.ErrorCode != 0 {
return &obj, NewError(obj.ErrorCode, obj.ErrorMessage)
}
return &obj, nil
}
func (c *Client) prepare() (*fasthttp.Request, *fasthttp.Response) {
var req = fasthttp.AcquireRequest()
var res = fasthttp.AcquireResponse()
var uri = req.URI()
uri.SetScheme(`https`)
uri.SetHost(`api.appmetrica.yandex.ru`)
req.Header.Set("User-Agent", `appmetrica/0.0.0+golang/1.11`)
req.Header.SetBytesV("Authorization", c.apikey)
return req, res
}