-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.go
More file actions
131 lines (98 loc) · 2.05 KB
/
fetch.go
File metadata and controls
131 lines (98 loc) · 2.05 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
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
120
121
122
123
124
125
126
127
128
129
130
131
package fetch
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Headers map[string]any
type Options[T any] struct {
Method string
Headers Headers
Body T
}
type Response[T any] struct {
Body T
Headers Headers
Status int
StatusText string
URL string
}
type Empty struct{}
var Client = &http.Client{}
func Fetch[T any, B any](address string, options Options[B]) (Response[T], error) {
if options.Method == "" {
options.Method = "GET"
}
var payload []byte
switch value := any(options.Body).(type) {
case []byte:
payload = value
case string:
payload = []byte(value)
case Empty:
// do nothing
default:
// TODO: check if `T` is non-json
var err error
payload, err = json.Marshal(value)
if err != nil {
return Response[T]{}, err
}
}
request, err := http.NewRequest(options.Method, address, bytes.NewBuffer(payload))
if err != nil {
return Response[T]{}, err
}
if len(options.Headers) > 0 {
for key, unknown := range options.Headers {
switch value := unknown.(type) {
case string:
request.Header.Add(key, value)
case []string:
for _, cursor := range value {
request.Header.Add(key, cursor)
}
default:
return Response[T]{}, fmt.Errorf("%T is not a supported header type", value)
}
}
}
response, err := Client.Do(request)
if err != nil {
return Response[T]{}, err
}
plain, err := io.ReadAll(response.Body)
if err != nil {
return Response[T]{}, err
}
var body T
switch any(body).(type) {
case string:
body = any(string(plain)).(T)
case []byte:
body = any(plain).(T)
default:
// TODO: check if `T` is non-json
err = json.Unmarshal(plain, &body)
if err != nil {
return Response[T]{}, err
}
}
headers := make(map[string]any)
for key, value := range response.Header {
if len(value) == 1 {
headers[key] = any(value[0])
} else {
headers[key] = any(value)
}
}
return Response[T]{
Body: body,
Headers: headers,
Status: response.StatusCode,
StatusText: response.Status,
URL: address,
}, nil
}