-
Notifications
You must be signed in to change notification settings - Fork 1
/
client_private.go
123 lines (103 loc) · 2.49 KB
/
client_private.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
114
115
116
117
118
119
120
121
122
123
package valuefirst
import (
"bytes"
"context"
"encoding/json"
"github.com/fairyhunter13/pool"
"github.com/fairyhunter13/reflecthelper/v5"
"github.com/gofiber/fiber/v2"
"net/http"
)
func (c *client) isError(resp *http.Response) bool {
return resp.StatusCode >= http.StatusBadRequest
}
func (c *client) getFullURL(subPath string) string {
return c.opt.BaseURL + subPath
}
func (c *client) setCustomIPs(req *http.Request) *client {
if len(c.opt.CustomIPs) <= 0 {
return c
}
for _, ip := range c.opt.CustomIPs {
req.Header.Add(fiber.HeaderXForwardedFor, ip)
}
return c
}
func (c *client) formatUnknownError(resp *http.Response) (err error) {
if !c.isError(resp) {
return
}
err = formatUnknown(resp)
return
}
func (c *client) getRequestTokenManagement(action string) (req *http.Request, err error) {
req, err = http.NewRequest(http.MethodPost, c.getFullURL(action), nil)
return
}
func (c *client) doRequestTokenManagement(ctx context.Context, req *http.Request, decode interface{}) (err error) {
if !reflecthelper.IsPtr(decode) {
err = ErrDecodeVarIsNotPtr
return
}
req.SetBasicAuth(c.opt.BasicAuth.User, c.opt.BasicAuth.Password)
req = req.WithContext(ctx)
resp, err := c.
setCustomIPs(req).
opt.client.Do(req)
if err != nil {
return
}
defer func() {
if resp.Body != nil {
_ = resp.Body.Close()
}
}()
err = c.formatUnknownError(resp)
if err != nil {
return
}
err = json.NewDecoder(resp.Body).Decode(decode)
return
}
func (c *client) putBuffer(buff *bytes.Buffer) {
pool.Put(buff)
}
func (c *client) getRequestSendSMS(action string, in interface{}) (req *http.Request, buff *bytes.Buffer, err error) {
buff = pool.GetBuffer()
err = json.NewEncoder(buff).Encode(in)
if err != nil {
return
}
req, err = http.NewRequest(http.MethodPost, c.getFullURL(action), buff)
return
}
func (c *client) doRequestSendSMS(ctx context.Context, req *http.Request, decode interface{}) (err error) {
if !reflecthelper.IsPtr(decode) {
err = ErrDecodeVarIsNotPtr
return
}
token, err := c.opt.TokenManager.Get(ctx)
if err != nil {
return
}
req.Header.Set(fiber.HeaderAuthorization, "Bearer "+token)
req.Header.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSON)
req = req.WithContext(ctx)
resp, err := c.
setCustomIPs(req).
opt.client.Do(req)
if err != nil {
return
}
defer func() {
if resp.Body != nil {
_ = resp.Body.Close()
}
}()
err = c.formatUnknownError(resp)
if err != nil {
return
}
err = json.NewDecoder(resp.Body).Decode(decode)
return
}