diff options
author | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2019-08-09 02:02:05 +0300 |
---|---|---|
committer | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2019-08-09 02:02:05 +0300 |
commit | 94c96cef29cd83bc60b2eabb8bb89c9fd8c7059b (patch) | |
tree | 676b3e2b6ffb171e102931e5fac01f7a4621c20a /client.go | |
parent | d13acd7da9bd1c08de33b91120a479df88d21db2 (diff) |
0.1.8 Release
Diffstat (limited to 'client.go')
-rw-r--r-- | client.go | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/client.go b/client.go new file mode 100644 index 0000000..39efbe8 --- /dev/null +++ b/client.go @@ -0,0 +1,56 @@ +// Package tamtam implements TamTam Bot API +// Copyright (c) 2019 Alexander Kiryukhin <a.kiryukhin@mail.ru> +package tamtam + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" +) + +type client struct { + key string + version string + url *url.URL +} + +func newClient(key string, version string, url *url.URL) *client { + return &client{key: key, version: version, url: url} +} + +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) { + c := http.DefaultClient + 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 := c.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 +} |