-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (94 loc) · 2.4 KB
/
main.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
package grx
import (
"bytes"
"encoding/json"
"io"
"net/http"
"time"
)
// TapsilatAPI is the main struct for the Tapsilat API
type API struct {
EndPoint string `json:"end_point"`
Token string `json:"token"`
}
// NewAPI creates a new TapsilatAPI struct
func NewAPI(token string) *API {
return &API{
EndPoint: "https://grc.tapsilat.dev/api/public",
Token: token,
}
}
// NewAPIWithEndpoint creates a new TapsilatAPI struct with a custom endpoint
func NewCustomAPI(endpoint, token string) *API {
return &API{
EndPoint: endpoint,
Token: token,
}
}
func (t *API) post(path string, payload interface{}, response interface{}) error {
url := t.EndPoint + path
jsonPayload, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
return t.do(req, response)
}
// update
func (t *API) put(path string, payload interface{}, response interface{}) error {
url := t.EndPoint + path
jsonPayload, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonPayload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
return t.do(req, response)
}
// func (t *API) get(path string, payload interface{}, response interface{}) error {
// url := t.EndPoint + path
// req, err := http.NewRequest("GET", url, nil)
// if err != nil {
// return err
// }
// return t.do(req, response)
// }
// func (t *API) delete(path string, payload interface{}, response interface{}) error {
// url := t.EndPoint + path
// req, err := http.NewRequest("DELETE", url, nil)
// if err != nil {
// return err
// }
// return t.do(req, response)
// }
func (t *API) do(req *http.Request, response interface{}) error {
req.Header.Set("data-api-key", t.Token)
client := &http.Client{
Timeout: 30 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
decode := json.NewDecoder(bytes.NewReader(body))
decode.DisallowUnknownFields()
decode.UseNumber()
if err := decode.Decode(response); err != nil {
return err
}
return nil
}
func (t *API) CreateData(payload CreateData) (CreateResponse, error) {
var response CreateResponse
err := t.post("/data", payload, &response)
return response, err
}