-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
87 lines (77 loc) · 2.02 KB
/
http.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
package goai
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"strconv"
)
func httpCatchErr(resp *http.Response) ([]byte, error) {
resBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Check for HTTP Response Errors
if resp.StatusCode != 200 {
errJson := ErrorResponse{}
err = json.Unmarshal(resBody, &errJson)
return nil, errors.New("API Error: " + strconv.Itoa(resp.StatusCode) + "\n" + errJson.Error.Message)
}
return resBody, nil
}
func (goai Client) MakeRequest(request *http.Request, responseJson interface{}) ([]byte, error) {
// Make the HTTP Request
resp, err := goai.HTTPClient.Do(request)
if err != nil {
return nil, err
}
// Check for HTTP Errors
jsonString, err := httpCatchErr(resp)
if err != nil {
return nil, err
}
if goai.Verbose {
b, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
fmt.Println("🌐 HTTP Response", b)
}
// Close the HTTP Response Body
defer resp.Body.Close()
if responseJson == nil {
return jsonString, nil
}
// Unmarshal the JSON Response Body into provided responseJson
err = json.Unmarshal([]byte(jsonString), &responseJson)
if err != nil {
return nil, errors.New("Error Unmarshalling JSON Response: " + err.Error())
}
if goai.Verbose {
// trace()
fmt.Println("🌐 HTTP Response String", string(jsonString))
fmt.Println("🌐 HTTP Response JSON", responseJson)
}
return jsonString, nil
}
func (goai Client) PostJson(requestJson, responseJson interface{}, endpoint string) ([]byte, error) {
// Marshal the JSON Request Body
requestBodyJson, err := json.Marshal(requestJson)
if err != nil {
return nil, err
}
if goai.Verbose {
fmt.Println(string(requestBodyJson))
}
// Format HTTP Response and Set Headers
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(requestBodyJson))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+goai.API_KEY)
return goai.MakeRequest(req, responseJson)
}