-
Notifications
You must be signed in to change notification settings - Fork 8
/
tag.go
92 lines (75 loc) · 1.68 KB
/
tag.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package upcloud
import (
"encoding/json"
)
// Tags represents a list of tags
type Tags struct {
Tags []Tag
}
// UnmarshalJSON is a custom unmarshaller that deals with
// deeply embedded values.
func (s *Tags) UnmarshalJSON(b []byte) error {
type localTag Tag
type tagWrapper struct {
Tags []localTag `json:"tag"`
}
v := struct {
Tags tagWrapper `json:"tags"`
}{}
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
for _, t := range v.Tags.Tags {
s.Tags = append(s.Tags, Tag(t))
}
return nil
}
// TagServerSlice is a slice of string.
// It exists to allow for a custom JSON unmarshaller.
type TagServerSlice []string
// UnmarshalJSON is a custom unmarshaller that deals with
// deeply embedded values.
func (t *TagServerSlice) UnmarshalJSON(b []byte) error {
v := struct {
Servers []string `json:"server"`
}{}
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
(*t) = v.Servers
return nil
}
// MarshalJSON is a custom marshaller that deals with
// deeply embedded values.
func (t TagServerSlice) MarshalJSON() ([]byte, error) {
v := struct {
Servers []string `json:"server"`
}{}
if t == nil {
t = make(TagServerSlice, 0)
}
v.Servers = t
return json.Marshal(v)
}
// Tag represents a server tag
type Tag struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Servers TagServerSlice `json:"servers"`
}
// UnmarshalJSON is a custom unmarshaller that deals with
// deeply embedded values.
func (s *Tag) UnmarshalJSON(b []byte) error {
type localTag Tag
v := struct {
Tag localTag `json:"tag"`
}{}
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
(*s) = Tag(v.Tag)
return nil
}