-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapi.go
More file actions
60 lines (48 loc) · 1.18 KB
/
Copy pathapi.go
File metadata and controls
60 lines (48 loc) · 1.18 KB
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
package ukrposhta
import (
"encoding/json"
"errors"
"github.com/RomaBilka/parcel-tracking/pkg/http"
"github.com/valyala/fasthttp"
)
const URL = "/statuses/"
type Api struct {
apiURL string
token string
}
func NewApi(apiURL, token string) *Api {
return &Api{
apiURL: apiURL,
token: token,
}
}
func (api *Api) TrackByTrackingNumber(barcodes []string) (*Response, error) {
data, err := json.Marshal(barcodes)
if err != nil {
return nil, err
}
b, err := api.makeRequest(data, "with-not-found", fasthttp.MethodGet)
if err != nil {
return nil, err
}
response := &Response{}
if err := json.Unmarshal(b, response); err != nil {
return nil, err
}
return response, err
}
func (api *Api) makeRequest(data []byte, path, method string) ([]byte, error) {
res, err := http.Do(api.apiURL+URL+path, method, func(req *fasthttp.Request) {
req.SetBody(data)
req.Header.SetContentType("application/json")
req.Header.Add("authorization", "Bearer "+api.token)
})
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()))
}