-
Notifications
You must be signed in to change notification settings - Fork 0
/
contextEntry.go
88 lines (69 loc) · 1.82 KB
/
contextEntry.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
package streams
import (
"encoding/json"
)
// ContextEntry
// https://www.w3.org/TR/json-ld/#the-context
type ContextEntry struct {
Vocabulary string // The primary vocabulary represented by the context/document.
Language string // The language
Extensions map[string]string // a map of additional namespaces that are included in this context/document.
}
func NewContextEntry(vocabulary string) ContextEntry {
return ContextEntry{
Vocabulary: vocabulary,
Language: "und",
Extensions: make(map[string]string),
}
}
func (entry *ContextEntry) WithLanguage(language string) *ContextEntry {
entry.Language = language
return entry
}
func (entry *ContextEntry) WithExtension(key string, value string) *ContextEntry {
if len(entry.Extensions) == 0 {
entry.Extensions = make(map[string]string)
}
entry.Extensions[key] = value
return entry
}
func (entry ContextEntry) MarshalJSON() ([]byte, error) {
// If this context only has a vocabulary, then
// use the short-form "string only" syntax
if entry.IsVocabularyOnly() {
return json.Marshal(entry.Vocabulary)
}
// Otherwise, use the long-form syntax as a JSON object
result := make(map[string]any)
result["@vocab"] = entry.Vocabulary
if entry.IsLanguageDefined() {
result["@language"] = entry.Language
}
if entry.HasExtensions() {
for key, value := range entry.Extensions {
result[key] = value
}
}
return json.Marshal(result)
}
func (entry ContextEntry) IsVocabularyOnly() bool {
if entry.IsLanguageDefined() {
return false
}
if entry.HasExtensions() {
return false
}
return true
}
func (entry ContextEntry) IsLanguageDefined() bool {
if entry.Language == "" {
return false
}
if entry.Language == "und" {
return false
}
return true
}
func (entry ContextEntry) HasExtensions() bool {
return len(entry.Extensions) > 0
}