-
Notifications
You must be signed in to change notification settings - Fork 1
/
decode.go
41 lines (32 loc) · 845 Bytes
/
decode.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
package patch
import (
"encoding/json"
"fmt"
)
// Decoder is the interface for types that can decode a response body.
type Decoder interface {
Name() string
Decode([]byte, interface{}) error
}
var jsonDecoder = &DecoderJSON{}
func inferDecoder(contentType string) (Decoder, error) {
switch contentType {
case "application/json",
"application/json; charset=utf-8":
return jsonDecoder, nil
}
return nil, ContentTypeError(contentType)
}
// DecoderJSON decodes JSON bodies
type DecoderJSON struct{}
// Name returns the name of the format
func (d *DecoderJSON) Name() string {
return "JSON"
}
// Decode unmarshals a JSON response body
func (d *DecoderJSON) Decode(data []byte, v interface{}) error {
if err := json.Unmarshal(data, v); err != nil {
return fmt.Errorf("failed to decode body as JSON: %w", err)
}
return nil
}