-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstring.go
68 lines (58 loc) · 1.36 KB
/
string.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package iamgo
import (
"encoding/json"
"fmt"
"github.com/liamg/jfather"
)
type String struct {
inner string
r Range
}
func (s *String) UnmarshalJSONWithMetadata(node jfather.Node) error {
s.r.StartLine = node.Range().Start.Line
s.r.EndLine = node.Range().End.Line
return node.Decode(&s.inner)
}
func (d String) MarshalJSON() ([]byte, error) {
return json.Marshal(d.inner)
}
type Strings struct {
inner innerStrings
r Range
}
func (s *Strings) UnmarshalJSONWithMetadata(node jfather.Node) error {
s.r.StartLine = node.Range().Start.Line
s.r.EndLine = node.Range().End.Line
if err := node.Decode(&s.inner); err == nil {
return nil
}
s.inner = []string{""}
return node.Decode(&s.inner[0])
}
type innerStrings []string
func (d Strings) MarshalJSON() ([]byte, error) {
return json.Marshal(d.inner)
}
func (v *innerStrings) UnmarshalJSONWithMetadata(node jfather.Node) error {
var raw interface{}
if err := node.Decode(&raw); err != nil {
return err
}
switch actual := raw.(type) {
case []string:
*v = actual
case []interface{}:
var output []string
for _, raw := range actual {
output = append(output, fmt.Sprintf("%s", raw))
}
*v = output
case string:
*v = []string{actual}
case bool:
*v = []string{fmt.Sprintf("%t", actual)}
default:
return fmt.Errorf("cannot use %T type for multi-value JSON field", actual)
}
return nil
}