This repository has been archived by the owner on Feb 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvk.go
77 lines (63 loc) · 1.88 KB
/
vk.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
package vk_api
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const (
version = 5.68
methodURL = "https://api.vk.com/method/"
)
// Client is a structure that holds access token that allows VK API to allow us to request methods and do some cool stuff. Neat!
type Client struct {
AccessToken string
}
// RequestParameters is an alias for map[string]interface{}
type RequestParameters map[string]interface{}
// NewClient returns an API structure and takes access token, error is returned if something goes wrong
func NewClient(authType authentication) (*Client, error) {
accessToken, err := authType.retrieveAccessToken()
if err != nil {
return nil, err
}
return &Client{accessToken}, nil
}
// Request function makes an API request and returns a slice of bytes that represent JSON requestResponse
func (client *Client) Request(method string, parameters RequestParameters) ([]byte, error) {
query := url.Values{
"access_token": {client.AccessToken},
"v": {fmt.Sprint(version)},
}
// add parameters to query
for key, value := range parameters {
query.Set(key, fmt.Sprint(value))
}
response, err := http.Get(fmt.Sprintf("%s?%s", methodURL+method, query.Encode()))
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
var requestResponse map[string]*json.RawMessage
if err = json.Unmarshal(body, &requestResponse); err != nil {
return nil, err
}
if err, ok := requestResponse["error"]; ok {
var errorData struct {
Code int `json:"error_code"`
Message string `json:"error_msg"`
}
json.Unmarshal(*err, &errorData)
return nil, fmt.Errorf("error #%d: %s", errorData.Code, errorData.Message)
}
if response, ok := requestResponse["response"]; ok {
return response.MarshalJSON()
}
return nil, errors.New("no response returned")
}