This repository was archived by the owner on Jan 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpRequest.go
More file actions
82 lines (66 loc) · 1.95 KB
/
httpRequest.go
File metadata and controls
82 lines (66 loc) · 1.95 KB
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
package ttRequests
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
)
var client = &http.Client{}
func Get_(url string, strucVar any) (*any, error) {
res, resErr := request(url)
if resErr != nil {
return nil, resErr
}
_, parseErr := parse(res, strucVar)
if parseErr != nil {
return nil, parseErr
}
return &strucVar, nil
}
func GetNoParse_(url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("X-Tycoon-Key", os.Getenv("TYCOON_KEY_PRIVATE"))
resp, err := client.Do(req)
if err != nil { // Pass on any HTTP error
fmt.Println(err)
return nil, errors.New("HTTP Error: " + err.Error())
}
return resp, nil
}
func parse(body string, parsed any) (*any, error) {
err := json.Unmarshal([]byte(body), &parsed) // Parse body string into the struct
if err != nil { // Pass on any JSON error
fmt.Println(err, body)
return nil, errors.New("JSON Error: " + err.Error())
}
return &parsed, nil // Return reference to parsed struct | If "parsed" is not passed as reference, it will return an empty struct
}
func request(url string) (string, error) {
// Make the request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Set("X-Tycoon-Key", os.Getenv("TYCOON_KEY_PRIVATE"))
resp, err := client.Do(req)
if err != nil { // Pass on any HTTP error
fmt.Println(err)
return "", errors.New("HTTP Error: " + err.Error())
}
body, err := ioutil.ReadAll(resp.Body) // Read the body into a string
if err != nil { // Pass on any READ error
fmt.Println(err)
return "", errors.New("READ Error: " + err.Error())
}
bodyContent := string(body)
if resp.StatusCode != 200 { // Pass on any HTTP error codes
fmt.Printf("Error code: %d.\nContent: %s\n", resp.StatusCode, bodyContent)
return "", errors.New("HTTP Error: " + resp.Status)
}
return bodyContent, nil
}