-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
70 lines (61 loc) · 2.38 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// GetJSON makes a GET request to url, then unmarshals the response body from JSON.
// Additional headers can be passed as a map.
func GetJSON[Res interface{}](url string, headers map[string][]string, responseBody *Res) error {
return requestJSON[interface{}, Res]("GET", url, headers, nil, responseBody)
}
// PostJSON makes a POST request to url, marshaling the request body to JSON and unmarshaling the response body from JSON.
// Method is set by argument, and additional headers can be passed as a map.
func PostJSON[Req interface{}, Res interface{}](url string, headers map[string][]string, requestBody *Req, responseBody *Res) error {
return requestJSON[Req, Res]("POST", url, headers, requestBody, responseBody)
}
// requestJSON makes an HTTP request, marshaling the request body to JSON and unmarshaling the response body from JSON.
// Method is set by argument, and additional headers can be passed as a map.
// For GET requests, Req should be interface{} and requestBody should be nil.
func requestJSON[Req interface{}, Res interface{}](method string, url string, headers map[string][]string, requestBody *Req, responseBody *Res) error {
var req *http.Request
var err error
if requestBody != nil { // If payload provided, marshal to JSON. Should be missing for GET.
// Don't shadow outer err in next assignment
payloadJson, marshalErr := json.Marshal(requestBody)
if marshalErr != nil {
return fmt.Errorf("failed to marshal request body to JSON: %w", err)
}
req, err = http.NewRequest(method, url, bytes.NewBuffer(payloadJson))
} else { // Probably a GET
req, err = http.NewRequest(method, url, nil)
}
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
// Set any extra headers
for k, v := range headers {
req.Header[k] = v
}
// Make request
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("got non-200 status: %d", res.StatusCode)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
err = json.Unmarshal(body, responseBody)
if err != nil {
return fmt.Errorf("failed to unmarshal response body: %w", err)
}
return nil
}