Debian Codegraph @

strslice/strslice.go

raw
1 package strslice
2
3 import "encoding/json"
4
5 // StrSlice represents a string or an array of strings.
6 // We need to override the json decoder to accept both options.
7 type StrSlice []string
8
9 // UnmarshalJSON decodes the byte slice whether it's a string or an array of
10 // strings. This method is needed to implement json.Unmarshaler.
11 func (e *StrSlice) UnmarshalJSON(b []byte) error {
12 if len(b) == 0 {
13 // With no input, we preserve the existing value by returning nil and
14 // leaving the target alone. This allows defining default values for
15 // the type.
16 return nil
17 }
18
19 p := make([]string, 0, 1)
20 if err := json.Unmarshal(b, &p); err != nil {
21 var s string
22 if err := json.Unmarshal(b, &s); err != nil {
23 return err
24 }
25 p = append(p, s)
26 }
27
28 *e = p
29 return nil
30 }