-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
70 lines (57 loc) · 1.4 KB
/
request.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
package cloudpayments
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
func (cp *cloudPayments) GenerateRequestURI(baseURL string, parts ...string) string {
var sb strings.Builder
sb.WriteString(baseURL + "/")
for index, part := range parts {
sb.WriteString(part)
if index != len(parts)-1 {
sb.WriteString("/")
}
}
return sb.String()
}
func (cp *cloudPayments) NewRequest(url string, body []byte) ([]byte, error) {
var (
client = &http.Client{}
bodyReader = bytes.NewReader(body)
)
req, err := http.NewRequest(http.MethodPost, url, bodyReader)
if err != nil {
err = fmt.Errorf("http.NewRequest: %w", err)
return nil, err
}
req.SetBasicAuth(cp.publicID, cp.apiSecret)
resp, err := client.Do(req)
if err != nil {
err = fmt.Errorf("client.Do: %w", err)
return nil, err
}
defer resp.Body.Close()
bt, err := io.ReadAll(resp.Body)
if err != nil {
err = fmt.Errorf("io.ReadAll: %w", err)
return nil, err
}
return bt, nil
}
func (cp *cloudPayments) GetPaymentResponse(requestURL string, data []byte) (*PaymentResponse, error) {
resp, err := cp.NewRequest(requestURL, data)
if err != nil {
err = fmt.Errorf("cp.NewRequest: %w", err)
return nil, err
}
var paymentResponse PaymentResponse
if err = json.Unmarshal(resp, &paymentResponse); err != nil {
err = fmt.Errorf("json.Unmarshal: %w", err)
return nil, err
}
return &paymentResponse, nil
}