aboutsummaryrefslogtreecommitdiff
path: root/client.go
blob: 7c5c0799e4b04734679dde8355ac32d28320654a (plain) (blame)
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
package tamtam

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
)

type client struct {
	key        string
	version    string
	url        *url.URL
	httpClient *http.Client
}

func newClient(key string, version string, url *url.URL, httpClient *http.Client) *client {
	return &client{key: key, version: version, url: url, httpClient: httpClient}
}

func (cl *client) request(method, path string, query url.Values, body interface{}) (io.ReadCloser, error) {
	j, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	return cl.requestReader(method, path, query, bytes.NewReader(j))
}

func (cl *client) requestReader(method, path string, query url.Values, body io.Reader) (io.ReadCloser, error) {
	u := *cl.url
	u.Path = path
	query.Set("access_token", cl.key)
	query.Set("v", cl.version)
	u.RawQuery = query.Encode()
	req, err := http.NewRequest(method, u.String(), body)
	if err != nil {
		return nil, err
	}
	resp, err := cl.httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		errObj := new(Error)
		err = json.NewDecoder(resp.Body).Decode(errObj)
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("code=%s message=%s error=%s", errObj.Code, errObj.Message, errObj.Error)
	}
	return resp.Body, err
}