-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
106 lines (90 loc) · 2.11 KB
/
api.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
package api
import (
"encoding/json"
"fmt"
"net/url"
"time"
"github.com/gorilla/schema"
"github.com/valyala/fasthttp"
)
const (
baseApiUrl = "https://api.vk.com/method/"
baseApiVersion = "5.131"
)
type Api struct {
Token string
Version string
Url string
Client *fasthttp.Client
Encoder *schema.Encoder
}
func NewApi(token string) *Api {
// Init Api struct
return &Api{
Url: baseApiUrl,
Token: token,
Version: baseApiVersion,
Client: &fasthttp.Client{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
MaxIdleConnDuration: time.Minute,
NoDefaultUserAgentHeader: true,
},
Encoder: schema.NewEncoder(),
}
}
func (api *Api) Method(methodName string, data map[string]string, target interface{}) error {
// Call to vk api method
params := fmt.Sprintf(
"?access_token=%s&v=%s",
api.Token, api.Version,
)
resUrl := api.Url + methodName + params
urlParams := url.Values{}
for key, value := range data {
urlParams.Add(key, value)
}
urlEncoded := urlParams.Encode()
reqEntityBytes := []byte(urlEncoded)
return api.Post(
resUrl,
reqEntityBytes,
target,
)
}
func (api *Api) Request(methodName string, data interface{}, target interface{}) error {
// Call to vk api method
params := fmt.Sprintf(
"?access_token=%s&v=%s",
api.Token, api.Version,
)
resUrl := api.Url + methodName + params
urlData := url.Values{}
if err := api.Encoder.Encode(data, urlData); err != nil {
return err
}
urlEncoded := urlData.Encode()
encodedData := []byte(urlEncoded)
return api.Post(
resUrl,
encodedData,
target,
)
}
func (api *Api) Post(url string, data []byte, target interface{}) error {
// Create POST request
req := fasthttp.AcquireRequest()
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(resp)
req.Header.SetMethod("POST")
req.Header.SetContentType("application/x-www-form-urlencoded")
req.SetRequestURI(url)
req.SetBody(data)
api.Client.Do(req, resp)
body := resp.Body()
if target == nil || len(body) == 0 {
return nil
}
return json.Unmarshal(body, target)
}