-
Notifications
You must be signed in to change notification settings - Fork 4
/
property-handle.go
74 lines (62 loc) · 1.6 KB
/
property-handle.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
package webthing
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// PropertyHandle a request to /properties/<property>.
type PropertyHandle struct {
*PropertiesHandle
*Property
}
// Handle a request to /properties/<property>.
func (h *PropertyHandle) Handle(w http.ResponseWriter, r *http.Request) {
name, err := resource(trimSlash(r.RequestURI))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
h.Property = h.properties[name]
BaseHandle(h, w, r)
}
// Get Handle a GET request.
//
// @param {Object} r The request object
// @param {Object} w The response object
func (h *PropertyHandle) Get(w http.ResponseWriter, r *http.Request) {
name := h.Property.Name()
value := h.Property.Value().Get()
description := make(map[string]interface{})
description[name] = value
content, err := json.Marshal(description)
if err != nil {
fmt.Println(err)
}
if _, err := w.Write(content); err != nil {
fmt.Println(err)
}
}
// Put Handle a PUT request.
//
// @param {Object} r The request object
// @param {Object} w The response object
func (h *PropertyHandle) Put(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
var obj map[string]interface{}
err := json.Unmarshal(body, &obj)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
name := h.Property.Name()
h.Property.Value().Set(obj[name])
description := make(map[string]interface{})
description[name] = h.Property.Value().Get()
content, _ := json.Marshal(description)
if _, err = w.Write(content); err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
}
}