forked from soltys/go-aftermarketpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
82 lines (62 loc) · 1.57 KB
/
transport.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
package aftermarketpl
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"github.com/google/go-querystring/query"
)
type emptyRequest struct {
}
type aftermarketResponse struct {
Ok int `json:"ok"`
Status int `json:"status"`
Error string `json:"error"`
}
//Send is basic function to send struct by request
func (a *Aftermarketpl) send(requestURL string, requestBody io.Reader) ([]byte, error) {
request, err := http.NewRequest("POST", requestURL, requestBody)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
request.SetBasicAuth(a.key, a.secret)
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
return body, nil
}
func encodeRequest(request interface{}) (io.Reader, error) {
urlValues, err := query.Values(request)
if err != nil {
return nil, err
}
return bytes.NewBufferString(urlValues.Encode()), nil
}
func parseResponse(response []byte, v interface{}) error {
afResponse := aftermarketResponse{}
err := json.Unmarshal(response, &afResponse)
if err != nil {
return errors.New("Response is not typical Aftermarket.pl response")
}
if afResponse.Ok == 0 {
return errors.New(afResponse.Error)
}
err = json.Unmarshal(response, &v)
if err != nil {
return err
}
return nil
}
func (a *Aftermarketpl) createActionURL(actionURL string) (string, error) {
return a.url + actionURL, nil
}