-
Notifications
You must be signed in to change notification settings - Fork 0
/
print.go
78 lines (64 loc) · 1.69 KB
/
print.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
package melhorenvio
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Mode string
const (
Mode_Private Mode = "private"
Mode_Public Mode = "public"
)
type PrintRequest struct {
Mode Mode `json:"mode"`
Orders []string `json:"orders"`
}
type PrintResponse struct {
Url string `json:"url"`
}
type PrintError struct {
Message string `json:"message"`
Errors map[string][]string `json:"errors"`
}
func (pe *PrintError) Error() string {
return "melhor envio: print: " + pe.Message
}
func (c *Client) Print(req *PrintRequest) (*PrintResponse, error) {
buf := &bytes.Buffer{}
err := json.NewEncoder(buf).Encode(req)
if err != nil {
return nil, err
}
httpReq, err := http.NewRequestWithContext(c.context, "POST", c.config.ApiUrl+"/api/v2/me/shipment/print", buf)
if err != nil {
return nil, err
}
httpResp, err := c.doRequest(httpReq)
if err != nil {
return nil, err
}
defer httpResp.Body.Close()
body, _ := io.ReadAll(httpResp.Body)
switch httpResp.StatusCode {
case http.StatusOK:
var resp *PrintResponse
err = json.Unmarshal(body, &resp)
if err != nil {
return nil, fmt.Errorf("melhor envio: print: unrecognized response: %v %v", httpResp.StatusCode, string(body))
}
return resp, nil
case http.StatusUnprocessableEntity, http.StatusBadRequest:
ret := &PrintError{}
err = json.Unmarshal(body, ret)
if err != nil {
return nil, fmt.Errorf("melhor envio: print: unrecognized response: %v %v", httpResp.StatusCode, string(body))
}
return nil, ret
case http.StatusUnauthorized:
return nil, ErrInvalidToken
default:
return nil, fmt.Errorf("melhor envio: print: unrecognized response: %v %v", httpResp.StatusCode, string(body))
}
}