-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaftership.go
73 lines (62 loc) · 1.39 KB
/
aftership.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
package aftership
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"strings"
)
var (
ErrUnexpectedResponseStatus = errors.New("unexpected response status")
)
type AfterShip struct {
key string
}
func New(key string) *AfterShip {
return &AfterShip{
key: key,
}
}
func (a *AfterShip) prepareAndSend(ctx context.Context, method, url string, body interface{}) (*http.Response, error) {
var bodyJSON []byte
var err error
if body != nil {
bodyJSON, err = json.Marshal(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequestWithContext(ctx, method, "https://api.aftership.com/v4"+url, bytes.NewReader(bodyJSON))
if err != nil {
return nil, err
}
req.Header.Set("aftership-api-key", a.key)
req.Header.Set("Content-Type", "application/json")
b, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
fmt.Println(string(b))
return http.DefaultClient.Do(req)
}
func formatError(source error, r *http.Response) error {
if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
var body struct {
Meta struct {
Code int
Message string
Type string
}
}
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
return err
}
return fmt.Errorf("%w: %s: %s", source, body.Meta.Type, body.Meta.Message)
} else {
return fmt.Errorf("%w: %s", source, r.Status)
}
}