-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequest.go
119 lines (91 loc) · 2.01 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
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
package shotstacksdkgolang
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type ReqMethod string
const (
POST ReqMethod = "POST"
GET ReqMethod = "GET"
)
type Request struct {
Method ReqMethod `json:"method"`
Data any `json:"data"`
Path string `json:"params"`
Config *Config `json:"config"`
}
func NewRequest() *Request {
return new(Request)
}
func (req *Request) SetMethod(method ReqMethod) *Request {
req.Method = method
return req
}
func (req *Request) SetData(data any) *Request {
req.Data = data
return req
}
func (req *Request) SetPath(path string) *Request {
req.Path = path
return req
}
func (req *Request) SetConfig(config *Config) *Request {
req.Config = config
return req
}
func (req *Request) Send() ([]byte, error) {
Url := fmt.Sprintf("https://api.shotstack.io/%v/%v", req.Config.Env, req.Path)
headers := map[string][]string{
"Content-Type": {"application/json"},
"Accept": {"application/json"},
"x-api-key": {req.Config.ApiKey},
}
client := &http.Client{}
switch req.Method {
case GET:
httpReq, err := http.NewRequest(http.MethodGet, Url, nil)
if err != nil {
return nil, err
}
httpReq.Header = headers
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bodyBytes, nil
case POST:
jsonData, err := json.MarshalIndent(req.Data, "", " ")
if err != nil {
return nil, err
}
fmt.Println(string(jsonData))
buff := bytes.NewBuffer(jsonData)
httpReq, err := http.NewRequest(http.MethodPost, Url, buff)
if err != nil {
return nil, err
}
httpReq.Header = headers
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bodyBytes, nil
default:
err := errors.New("request method is invalid")
return nil, err
}
}