-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrest_client.go
More file actions
157 lines (136 loc) · 4.36 KB
/
rest_client.go
File metadata and controls
157 lines (136 loc) · 4.36 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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package paystack
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
)
const Version = "0.1.0"
const BaseUrl = "https://api.paystack.co"
var ErrNoSecretKey = errors.New("Paystack secret key was not provided")
// ClientOptions is a type used to modify attributes of an APIClient. It can be passed into the NewAPIClient
// function while creating an APIClient
type ClientOptions = func(client *restClient)
type restClient struct {
secretKey string
baseUrl string
httpClient *http.Client
}
// WithSecretKey lets you set the secret key of an APIClient. It should be used when creating an APIClient
// with the NewAPIClient function.
//
// Example
//
// import p "github.com/gray-adeyi/paystack"
// client := p.NewAPIClient(p.WithSecretKey("<your-paystack-secret-key>"))
func WithSecretKey(secretKey string) ClientOptions {
return func(client *restClient) {
client.secretKey = secretKey
}
}
// WithBaseUrl lets you override paystack's base url for an APIClient. It should be used when creating an APIClient
// with the NewAPIClient function.
func WithBaseUrl(baseUrl string) ClientOptions {
return func(client *restClient) {
client.baseUrl = baseUrl
}
}
func (a *restClient) APICall(ctx context.Context, method string, endPointPath string, payload any, response any) error {
var body *bytes.Buffer
var apiRequest *http.Request
var err error
if payload != nil {
payloadInBytes, err := json.Marshal(payload)
if err != nil {
return err
}
body = bytes.NewBuffer(payloadInBytes)
}
if payload != nil {
apiRequest, err = http.NewRequestWithContext(ctx, method, a.baseUrl+endPointPath, body)
} else {
apiRequest, err = http.NewRequestWithContext(ctx, method, a.baseUrl+endPointPath, nil)
}
if err != nil {
return err
}
err = a.setHeaders(apiRequest)
if err != nil {
return err
}
r, err := a.httpClient.Do(apiRequest)
if err != nil {
return err
}
return a.unMarshalResponse(r, response)
}
func (a *restClient) unMarshalResponse(httpResponse *http.Response, result any) error {
raw, err := io.ReadAll(httpResponse.Body)
if err != nil {
return err
}
if err = json.Unmarshal(raw, result); err != nil {
return err
}
// Get the value of the response interface
value := reflect.ValueOf(result)
// Check if it's a pointer and get the element it points to
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
// Check if it's a struct
if value.Kind() != reflect.Struct {
return fmt.Errorf("expected a struct of the generic model.Response struct, got %v", value.Kind())
}
// Check for StatusCode field
statusCodeField := value.FieldByName("StatusCode")
if !statusCodeField.IsValid() {
return errors.New("response parameter has no StatusCode field, please ensure response type is of the generic model.Response struct")
}
// Check if StatusCode field is settable and of correct type
if statusCodeField.CanSet() {
switch statusCodeField.Kind() {
case reflect.Int, reflect.Int32, reflect.Int64:
statusCodeField.SetInt(int64(httpResponse.StatusCode))
default:
return errors.New("StatusCode field of the response parameter is not a valid integer")
}
} else {
return errors.New("StatusCode field of the response parameter cannot be set")
}
// Check for Raw field
rawField := value.FieldByName("Raw")
if !rawField.IsValid() {
return errors.New("response parameter has no Raw field, please ensure response type is of the generic model.Response struct")
}
// Check if Raw field is settable and of correct type
if rawField.CanSet() {
switch rawField.Kind() {
case reflect.Slice:
if rawField.Type().Elem().Kind() == reflect.Uint8 {
rawField.SetBytes(raw)
}
default:
return errors.New("StatusCode field of the response parameter is not a valid integer")
}
} else {
return errors.New("StatusCode field of the response parameter cannot be set")
}
if httpResponse.StatusCode < http.StatusOK || httpResponse.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf("Request failed with status: %d", httpResponse.StatusCode)
}
return nil
}
func (a *restClient) setHeaders(request *http.Request) error {
if a.secretKey == "" {
return ErrNoSecretKey
}
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", a.secretKey))
request.Header.Set("User-Agent", fmt.Sprintf("github.com/gray-adeyi/paystack version %s", Version))
request.Header.Add("Content-Type", "application/json")
return nil
}