forked from ctdk/goiardi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nodes.go
96 lines (90 loc) · 2.74 KB
/
nodes.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
89
90
91
92
93
94
95
96
/* Node functions */
/*
* Copyright (c) 2013-2014, Jeremy Bingham (<jbingham@gmail.com>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"net/http"
"encoding/json"
"github.com/ctdk/goiardi/node"
"github.com/ctdk/goiardi/util"
)
func node_handler(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
node_name := r.URL.Path[7:]
/* So, what are we doing? Depends on the HTTP method, of course */
switch r.Method {
case "GET", "DELETE":
chef_node, err := node.Get(node_name)
if err != nil {
JsonErrorReport(w, r, err.Error(), http.StatusNotFound)
return
}
enc := json.NewEncoder(w)
if err = enc.Encode(&chef_node); err != nil {
JsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)
return
}
if r.Method == "DELETE" {
err = chef_node.Delete()
if err != nil {
JsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)
return
}
}
case "PUT":
node_data, jerr := ParseObjJson(r.Body)
if jerr != nil {
JsonErrorReport(w, r, jerr.Error(), http.StatusBadRequest)
return
}
chef_node, err := node.Get(node_name)
if err != nil {
JsonErrorReport(w, r, err.Error(), http.StatusNotFound)
return
}
/* If node_name and node_data["name"] don't match, we
* need to make a new node. Make sure that node doesn't
* exist. */
if _, found := node_data["name"]; !found {
node_data["name"] = node_name
}
json_name, sterr := util.ValidateAsString(node_data["name"])
if sterr != nil {
JsonErrorReport(w, r, sterr.Error(), http.StatusBadRequest)
return
}
if node_name != json_name && json_name != "" {
JsonErrorReport(w, r, "Node name mismatch.", http.StatusBadRequest)
return
} else {
if json_name == "" {
node_data["name"] = node_name
}
nerr := chef_node.UpdateFromJson(node_data)
if nerr != nil {
JsonErrorReport(w, r, nerr.Error(), nerr.Status())
return
}
}
chef_node.Save()
enc := json.NewEncoder(w)
if err = enc.Encode(&chef_node); err != nil {
JsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)
}
default:
JsonErrorReport(w, r, "Unrecognized method!", http.StatusMethodNotAllowed)
}
}