-
Notifications
You must be signed in to change notification settings - Fork 2
/
link.go
75 lines (63 loc) · 1.8 KB
/
link.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
package stac
import (
"encoding/json"
"regexp"
"github.com/go-viper/mapstructure/v2"
)
type Link struct {
Href string `mapstructure:"href"`
Rel string `mapstructure:"rel"`
Type string `mapstructure:"type,omitempty"`
Title string `mapstructure:"title,omitempty"`
Extensions []Extension `mapstructure:"-"`
AdditionalFields map[string]any `mapstructure:",remain"`
}
var linkExtensions = newExtensionRegistry()
func RegisterLinkExtension(pattern *regexp.Regexp, provider ExtensionProvider) {
linkExtensions.register(pattern, provider)
}
func GetLinkExtension(uri string) Extension {
return linkExtensions.get(uri)
}
func EncodeLinks(links []*Link) ([]map[string]any, []string, error) {
extensionUris := []string{}
linksData := make([]map[string]any, len(links))
for i, link := range links {
linkMap := map[string]any{}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: &linkMap,
})
if err != nil {
return nil, nil, err
}
if err := decoder.Decode(link); err != nil {
return nil, nil, err
}
for _, extension := range link.Extensions {
extensionUris = append(extensionUris, extension.URI())
if err := extension.Encode(linkMap); err != nil {
return nil, nil, err
}
}
linksData[i] = linkMap
}
return linksData, extensionUris, nil
}
var (
_ json.Marshaler = (*Link)(nil)
_ json.Unmarshaler = (*Link)(nil)
)
func (link *Link) MarshalJSON() ([]byte, error) {
m := map[string]any{}
if err := mapstructure.Decode(link, &m); err != nil {
return nil, err
}
return json.Marshal(m)
}
func (link *Link) UnmarshalJSON(data []byte) error {
m := map[string]any{}
if err := json.Unmarshal(data, &m); err != nil {
return err
}
return mapstructure.Decode(m, link)
}