-
Notifications
You must be signed in to change notification settings - Fork 17
/
json.go
51 lines (45 loc) · 1.09 KB
/
json.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
// Package json provides functions to facilitate dealing with JSON.
package json
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// Reader takes an input, marshal it to JSON and returns a io.Reader of it.
func Reader[T any](v T) io.Reader {
bts, err := json.Marshal(v)
if err != nil {
return &ErrorReader{err}
}
return bytes.NewReader(bts)
}
// ErrorReader is a reader that always errors with the given error.
type ErrorReader struct {
err error
}
func (r *ErrorReader) Read(_ []byte) (int, error) {
return 0, r.err
}
// From parses a io.Reader with JSON.
func From[T any](r io.Reader, t T) (T, error) {
bts, err := io.ReadAll(r)
if err != nil {
return t, fmt.Errorf("failed to read response: %w", err)
}
if err := json.Unmarshal(bts, &t); err != nil {
return t, fmt.Errorf("failed to parse body: %w: %s", err, bts)
}
return t, nil
}
// Write writes the given data as JSON.
func Write(w http.ResponseWriter, data any) error {
bts, err := json.Marshal(data)
if err != nil {
return err
}
w.Header().Add("Content-Type", "application/json")
_, err = w.Write(bts)
return err
}