1package resp
2
3// A Field contains metadata about a JSON field that was
4// unmarshalled from a response.
5//
6// To check if the field was unmarshalled successfully, use the [Field.IsPresent] method.
7//
8// Use the [Field.IsExplicitNull] method to check if the JSON value is "null".
9//
10// If the [Field.Raw] is the empty string, then the field was omitted.
11//
12// Otherwise, if the field was invalid and couldn't be marshalled successfully, [Field.IsPresent] will be false,
13// and [Field.Raw] will not be empty.
14type Field struct {
15 status
16 raw string
17}
18
19const (
20 omitted status = iota
21 null
22 invalid
23 valid
24)
25
26type status int8
27
28// IsPresent returns true if the field was unmarshalled successfully.
29// If IsPresent is false, the field was either omitted, the JSON value "null", or an unexpected type.
30func (j Field) IsPresent() bool { return j.status > invalid }
31
32// Returns true if the field is the JSON value "null".
33func (j Field) IsExplicitNull() bool { return j.status == null }
34
35// Returns the raw JSON value of the field.
36func (j Field) Raw() string {
37 if j.status == omitted {
38 return ""
39 }
40 return j.raw
41}
42
43func NewValidField(raw string) Field {
44 if raw == "null" {
45 return NewNullField()
46 }
47 return Field{raw: raw, status: valid}
48}
49
50func NewNullField() Field {
51 return Field{status: null}
52}
53
54func NewInvalidField(raw string) Field {
55 return Field{status: invalid, raw: raw}
56}