-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.go
More file actions
51 lines (44 loc) · 1.3 KB
/
decode.go
File metadata and controls
51 lines (44 loc) · 1.3 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
package json_decoder
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
var (
ErrInvalidJSON = errors.New("invalid json")
ErrRequestEntityTooLarge = errors.New("request entity too large")
)
func Decode(r io.Reader, v any) error {
d := json.NewDecoder(r)
d.DisallowUnknownFields()
if err := d.Decode(&v); err != nil {
var (
httpMaxBytesError *http.MaxBytesError
jsonSyntaxError *json.SyntaxError
jsonUnmarshalTypeError *json.UnmarshalTypeError
)
switch {
case strings.HasPrefix(err.Error(), "json: unknown field "): // https://github.com/golang/go/issues/29035
return fmt.Errorf("%w: %w", ErrInvalidJSON, err)
case errors.Is(err, io.EOF):
return fmt.Errorf("%w: %w", ErrInvalidJSON, err)
case errors.Is(err, io.ErrUnexpectedEOF): // https://github.com/golang/go/issues/25956
return fmt.Errorf("%w: %w", ErrInvalidJSON, err)
case errors.As(err, &httpMaxBytesError):
return fmt.Errorf("%w: %w", ErrRequestEntityTooLarge, err)
case errors.As(err, &jsonSyntaxError):
return fmt.Errorf("%w: %w", ErrInvalidJSON, err)
case errors.As(err, &jsonUnmarshalTypeError):
return fmt.Errorf("%w: %w", ErrInvalidJSON, err)
default:
return fmt.Errorf("decoder.Decode: %w", err)
}
}
if d.More() {
return ErrInvalidJSON
}
return nil
}