-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
92 lines (82 loc) · 1.82 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
package iyzigo
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"sync"
)
type (
Options struct {
ApiKey string
SecretKey string
BaseUrl string
}
client struct {
Options
}
iyzicoLog struct {
Request interface{} `json:"request,omitempty"`
Response interface{} `json:"response,omitempty"`
Error string `json:"error,omitempty"`
}
)
var (
once sync.Once
options Options
c *client
)
func getClient() *client {
once.Do(func() {
c = &client{
Options: options,
}
})
return c
}
func IsProd() bool {
return !strings.HasPrefix(getClient().ApiKey, "sandbox-")
}
func sendToIyzicoApi(method string, endpoint string, object interface{}) (output []byte, err error) {
b, err := json.Marshal(object)
if err != nil {
logError(err)
return nil, err
}
req, err := http.NewRequest(method, fmt.Sprintf("%s%s", getClient().BaseUrl, endpoint), bytes.NewReader(b))
if err != nil {
logError(err)
return nil, err
}
req.Header = getClient().getHttpHeader(object)
hc := http.Client{}
hc.Transport = &http.Transport{DisableCompression: true}
il := iyzicoLog{Request: maskSensitiveInfo(object)}
res, err := hc.Do(req)
if err != nil {
logError(err)
return nil, err
}
defer res.Body.Close()
output, err = ioutil.ReadAll(res.Body)
if err != nil {
logError(err)
}
il.Response = string(output)
logRequest(il)
return
}
func doGet(endpoint string) ([]byte, error) {
return sendToIyzicoApi("GET", endpoint, nil)
}
func doPost(endpoint string, object interface{}) ([]byte, error) {
return sendToIyzicoApi("POST", endpoint, object)
}
func doPut(endpoint string, object interface{}) ([]byte, error) {
return sendToIyzicoApi("PUT", endpoint, object)
}
func doDelete(endpoint string, object interface{}) ([]byte, error) {
return sendToIyzicoApi("DELETE", endpoint, object)
}