-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
106 lines (87 loc) · 1.83 KB
/
client.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
package smmssdk
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
)
type Requester interface {
Request(ctx context.Context) (*http.Request, error)
}
type Responder interface {
}
type baseResponse struct {
Success bool `json:"success"`
Code string `json:"code"`
Message string `json:"message"`
RequestId string `json:"RequestId"`
Data *interface{} `json:"data,omitempty"`
}
type Client struct {
Options
baseURL string
respBodyRaw string
}
const (
baseURL = "https://sm.ms/api/v2"
)
func NewClient(options ...Option) *Client {
c := new(Client)
c.baseURL = baseURL
c.logger = slog.Default()
c.logEnabled = false
for _, option := range options {
option(c)
}
return c
}
func (c *Client) Do(ctx context.Context, request Requester, responder Responder) error {
err := c.do(ctx, request, responder)
if err != nil {
return err
}
return nil
}
func (c *Client) do(ctx context.Context, request Requester, response Responder) error {
req, err := request.Request(ctx)
if err != nil {
return err
}
if c.secretToken != "" {
req.Header.Set("Authorization", c.secretToken)
}
if c.logEnabled {
c.logger.InfoContext(ctx, "starting request",
slog.String("method", req.Method),
slog.String("url", req.URL.String()),
//slog.Any("headers", req.Header),
)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var buf bytes.Buffer
//io.TeeReader(resp.Body, &buf)
_, err = io.Copy(&buf, resp.Body)
if err != nil {
return err
}
// response raw text
c.respBodyRaw = buf.String()
if c.logEnabled {
c.logger.Info("response",
slog.Int("status code", resp.StatusCode),
slog.String("body raw", c.respBodyRaw),
)
}
// response json to struct
err = json.NewDecoder(&buf).Decode(response)
if err != nil {
return err
}
return nil
}