-
Notifications
You must be signed in to change notification settings - Fork 1
/
io.go
56 lines (44 loc) · 1.01 KB
/
io.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
package elephantine
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
func UnmarshalFile(path string, o interface{}) error {
contents, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
dec := json.NewDecoder(bytes.NewReader(contents))
dec.DisallowUnknownFields()
err = dec.Decode(o)
if err != nil {
return fmt.Errorf("failed to unmarshal JSON: %w", err)
}
return nil
}
func UnmarshalHTTPResource(resURL string, o interface{}) error {
res, err := http.Get(resURL) //nolint:gosec
if err != nil {
return fmt.Errorf("failed to perform request: %w", err)
}
defer func() {
err := res.Body.Close()
if err != nil {
log.Printf("failed to close %q response body: %v",
resURL, err)
}
}()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("server responded with: %q", res.Status)
}
dec := json.NewDecoder(res.Body)
err = dec.Decode(o)
if err != nil {
return fmt.Errorf("failed to unmarshal JSON: %w", err)
}
return nil
}