-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.go
65 lines (53 loc) · 1.3 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
package usps
import (
"encoding/xml"
"errors"
"github.com/RomaBilka/parcel-tracking/pkg/http"
"github.com/valyala/fasthttp"
)
type Api struct {
apiURL string
userId string
sourceId string
}
func NewApi(apiURL, userId, sourceId string) *Api {
return &Api{
apiURL: apiURL,
userId: userId,
sourceId: sourceId,
}
}
func (api *Api) TrackByTrackingNumber(trackNumbers []TrackID) (*TrackResponse, error) {
t := TrackFieldRequest{
Revision: 1,
TrackID: trackNumbers,
}
b, err := api.makeRequest(t, fasthttp.MethodPost, api.apiURL)
if err != nil {
return nil, err
}
trackResponse := &TrackResponse{}
if err := xml.Unmarshal(b, trackResponse); err != nil {
return nil, err
}
return trackResponse, nil
}
func (api *Api) makeRequest(t TrackFieldRequest, method, endPoint string) ([]byte, error) {
requestByte, err := xml.MarshalIndent(t, "", " ")
if err != nil {
return nil, err
}
data := append([]byte(xml.Header), requestByte...)
res, err := http.Do(endPoint, method, func(req *fasthttp.Request) {
req.Header.SetContentType(http.XmlContentType)
req.SetBody(data)
})
if err != nil {
return nil, err
}
defer fasthttp.ReleaseResponse(res)
if res.StatusCode() == fasthttp.StatusOK {
return res.Body(), nil
}
return nil, errors.New(fasthttp.StatusMessage(res.StatusCode()))
}