-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
52 lines (45 loc) · 1.2 KB
/
http.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
package openpay
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/pkg/errors"
)
func (c *client) newRequest(method, resource string, data interface{}) (*http.Request, error) {
url := fmt.Sprintf("%s/%s/%s", c.apiBase, c.merchantID, resource)
var body bytes.Buffer
enc := json.NewEncoder(&body)
if err := enc.Encode(data); err != nil {
return nil, errors.Wrap(err, "error encoding JSON")
}
req, err := http.NewRequest(method, url, &body)
if err != nil {
return nil, errors.Wrap(err, "error creating request")
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(c.privateKey, "")
return req, nil
}
func (c *client) perform(req *http.Request, dst interface{}) error {
res, err := c.client.Do(req)
if err != nil {
return errors.Wrap(err, "error performing request")
}
dec := json.NewDecoder(res.Body)
if res.StatusCode >= 400 {
var apiErr APIError
if err = dec.Decode(&apiErr); err != nil && err != io.EOF {
return errors.Wrap(err, "error decoding api error from JSON")
}
apiErr.HTTPCode = res.StatusCode
return &apiErr
}
if dst != nil {
if err = dec.Decode(&dst); err != nil {
return errors.Wrap(err, "error decoding JSON")
}
}
return nil
}