-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhal.go
More file actions
68 lines (55 loc) · 1.45 KB
/
hal.go
File metadata and controls
68 lines (55 loc) · 1.45 KB
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 main
import (
"encoding/json"
"net/url"
"github.com/ant0ine/go-json-rest/rest"
)
// SimpleHREF wraps a string href into a hal href object in json
type SimpleHREF string
// MarshalJSON serializes the uri as {"href": <uri>}
func (s SimpleHREF) MarshalJSON() ([]byte, error) {
return json.Marshal(
struct {
HREF string `json:"href"`
}{
string(s),
},
)
}
type halResponseWriter struct {
rest.ResponseWriter
}
// Links is a helper type to abbreviate map[string]interface{}
type Links map[string]interface{}
const omit = ",omitempty"
type HalResponse struct {
Links map[string]interface{} `json:"_links,omitempty"`
}
func MakeHalResponse() *HalResponse {
return &HalResponse{Links: make(map[string]interface{}, 1)}
}
func (h *HalResponse) SetSelf(url string) {
if h.Links == nil {
h.Links = make(map[string]interface{}, 1)
}
h.Links["self"] = SimpleHREF(url)
}
type HalResponseType interface {
SetSelf(string)
}
/*
WriteJSONResponse provides a wrapper on JSON marshalling that
makes it easier to support some aspects of the HAL specification -
specifically embedding the _links field in the root of the object, alongside
other fields.
It has only the most basic support for json tags and may fail in all but the most
simple cases.
*/
func (rw halResponseWriter) WriteJSONResponse(
self *url.URL,
re HalResponseType,
) error {
rw.Header().Set("Content-Type", "application/hal+json")
re.SetSelf("/api" + self.Path)
return rw.WriteJson(re)
}