-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
74 lines (61 loc) · 1.63 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
package providusbank
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/sirupsen/logrus"
)
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}
type client struct {
httpClient HttpClient
logger *logrus.Logger
}
// ClientOption is a function that configures a Client.
type ClientOption func(*client)
// WithHTTPClient sets the HTTP client for the paystack API client.
func WithHTTPClient(c HttpClient) ClientOption {
return func(target *client) {
target.httpClient = c
}
}
// WithLogger sets the *logrus.Logger for the paystack API client.
func WithLogger(l *logrus.Logger) ClientOption {
return func(target *client) {
target.logger = l
}
}
func (c *client) do(ctx context.Context, req *request) error {
resp, err := c.httpClient.Do(req.req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
if c.logger != nil {
c.logger.WithContext(ctx).WithFields(logrus.Fields{
"http.response.status_code": resp.StatusCode,
"http.response.body.content": string(b),
"http.response.headers": resp.Header,
}).Debug("providusbank.client -> response")
}
if resp.StatusCode >= 500 {
var errResponse ErrResponse
if err := json.Unmarshal(b, &errResponse); err != nil {
return fmt.Errorf("cannot decode err response: %w", err)
}
return errResponse
}
if req.decodeTo != nil {
if err := json.Unmarshal(b, req.decodeTo); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
}
return nil
}