-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshipment.go
113 lines (90 loc) · 2.29 KB
/
shipment.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
107
108
109
110
111
112
113
package ups
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
func (c *Client) CreateShipment(ctx context.Context, shipmentRequest ShipmentRequest) (*ShipmentResponse, error) {
jsonBody, err := json.MarshalIndent(struct {
ShipmentRequest ShipmentRequest
}{
ShipmentRequest: shipmentRequest,
}, "", " ")
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("%s%s", c.environment, shipmentURL), bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
err = c.addAuthorization(ctx, req)
if err != nil {
return nil, err
}
err = c.logHTTPRequest(req)
if err != nil {
return nil, err
}
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
err = c.logHTTPResponse(res)
if err != nil {
return nil, err
}
var response struct {
ShipmentResponse *ShipmentResponse
ErrorResponse *ErrorResponse `json:"response"`
}
err = json.NewDecoder(res.Body).Decode(&response)
if err != nil {
return nil, err
}
if response.ErrorResponse != nil {
return nil, response.ErrorResponse
}
return response.ShipmentResponse, nil
}
func (c *Client) VoidShipment(ctx context.Context, shipmentIdentificationNumber string) (*VoidShipmentResponse, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, fmt.Sprintf("%s%s/cancel/%s", c.environment, shipmentURL, shipmentIdentificationNumber), nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
err = c.addAuthorization(ctx, req)
if err != nil {
return nil, err
}
err = c.logHTTPRequest(req)
if err != nil {
return nil, err
}
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
err = c.logHTTPResponse(res)
if err != nil {
return nil, err
}
var response struct {
VoidShipmentResponse *VoidShipmentResponse
ErrorResponse *ErrorResponse `json:"response"`
}
err = json.NewDecoder(res.Body).Decode(&response)
if err != nil {
return nil, err
}
if response.ErrorResponse != nil {
return nil, response.ErrorResponse
}
return response.VoidShipmentResponse, nil
}