-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlink.go
61 lines (48 loc) · 1.36 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
package jsonapi
import (
"encoding/json"
"strings"
)
// Link represents a JSON:API links object.
type Link struct {
HRef string `json:"href"`
Meta map[string]any `json:"meta"`
}
// MarshalJSON builds the JSON representation of a Link object.
func (l Link) MarshalJSON() ([]byte, error) {
if len(l.Meta) > 0 {
var err error
m := map[string]json.RawMessage{}
m["href"], _ = json.Marshal(l.HRef)
m["meta"], err = json.Marshal(l.Meta)
if err != nil {
return []byte{}, err
}
return json.Marshal(m)
}
return json.Marshal(l.HRef)
}
// buildSelfLink builds a URL that points to the resource represented by the
// value v.
//
// prepath is prepended to the path and usually represents a scheme and a
// domain name.
func buildSelfLink(res Resource, prepath string) string {
link := prepath
if !strings.HasSuffix(prepath, "/") {
link += "/"
}
id, _ := res.Get("id").(string)
if id != "" && res.GetType().Name != "" {
link += res.GetType().Name + "/" + id
}
return link
}
// buildRelationshipLinks builds a links object (according to the JSON:API
// specification) that include both the self and related members.
func buildRelationshipLinks(res Resource, prepath, rel string) map[string]string {
return map[string]string{
"self": buildSelfLink(res, prepath) + "/relationships/" + rel,
"related": buildSelfLink(res, prepath) + "/" + rel,
}
}