-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjcliFetch.go
More file actions
75 lines (61 loc) · 1.99 KB
/
jcliFetch.go
File metadata and controls
75 lines (61 loc) · 1.99 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
func fetch(apiUrl string, authToken string) (map[string]interface{}, error) {
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
return map[string]interface{}{}, fmt.Errorf("%w", err)
}
req.Header.Add("Authorization", "Bearer "+authToken)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return map[string]interface{}{}, fmt.Errorf("%w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("\033[91mError reading response: %v\033[0m", err)
return map[string]interface{}{}, fmt.Errorf("error reading response: %w", err)
}
var data map[string]interface{}
if err := json.Unmarshal(body, &data); err != nil {
log.Fatalf("\033[91mError unmarshaling JSON: %v\033[0m", err)
return map[string]interface{}{}, fmt.Errorf("error unmarshaling JSON: %w", err)
}
return data, nil
}
func apiPost(apiUrl string, authToken string, body map[string]interface{}) (map[string]interface{}, error) {
jsonData, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("failed to marshal JSON: %w", err)
}
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+authToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("\033[91mError reading response: %v\033[0m", err)
return map[string]interface{}{}, fmt.Errorf("\033[91mError reading response: %v\033[0m", err)
}
var data map[string]interface{}
if err := json.Unmarshal(respBody, &data); err != nil {
return map[string]interface{}{}, fmt.Errorf("\033[91mError unmarshaling JSON: %v\033[0m", err)
}
return data, nil
}