-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
312 lines (230 loc) · 6.04 KB
/
server.go
File metadata and controls
312 lines (230 loc) · 6.04 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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package main
import (
"os"
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
type Task struct {
Id string `json:"id"`
Name string `json:"name"`
Complete bool `json:"complete"`
// Tags []string `json:"tags"`
}
const filepath = "/mnt/data/tasks.json"
var logging = logrus.New()
var log = logging.WithFields(logrus.Fields{"db": filepath})
/*
* Fetch the database into an array of tasks
*/
func fetchDB() []Task {
file, err := os.OpenFile(filepath, os.O_RDONLY, 0644)
if err != nil {
log.Error("Error opening the database")
}
defer file.Close()
bv, err := ioutil.ReadAll(file)
if err != nil {
log.Error("Error reading the database")
}
var tasks []Task
json.Unmarshal(bv, &tasks)
return tasks
}
/*
* Write the tasks to the database
*/
func writeDB(tasks []Task) {
res, err := json.Marshal(tasks)
if err != nil {
log.Error("Couldn't marshal json")
}
err = os.Truncate(filepath, 0)
if err != nil {
log.Error("Could not truncate file")
}
file, err := os.OpenFile(filepath, os.O_WRONLY, 0644)
if err != nil {
log.Error("Error opening the database")
}
defer file.Close()
file.Write(res)
}
/*
* Add a task to the database
*/
func addDB(newtask Task) {
log.WithFields(logrus.Fields{
"task": newtask,
}).Info("Adding task to database")
tasks := fetchDB()
tasks = append(tasks, newtask)
writeDB(tasks)
}
/*
* Update an entry in the database
* CHANGEME
*/
func updateDB(w http.ResponseWriter, id string, updated Task) {
tasks := fetchDB()
for i, _ := range tasks {
if tasks[i].Id == id {
fmt.Fprintf(w, "Updating %s", tasks[i].Name)
if updated.Name != "" {
tasks[i].Name = updated.Name
}
if tasks[i].Complete != updated.Complete {
tasks[i].Complete = updated.Complete
}
}
}
log.WithFields(logrus.Fields{
"task": updated,
}).Info("Updating task in database")
writeDB(tasks)
}
/*
* [ Handler ] Create a task
*/
func createTask(w http.ResponseWriter, r *http.Request) {
log.Info("Creating task")
var newtask Task
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, "Incorrect request")
}
log.WithFields(logrus.Fields{
"task": string(body),
}).Info("Received task input")
json.Unmarshal(body, &newtask)
addDB(newtask)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newtask)
}
/*
* [ Handler ] Retreive a single task
*/
func getOneTask(w http.ResponseWriter, r *http.Request) {
log.Info("Retrieving task")
tasks := fetchDB()
id := mux.Vars(r)["id"]
for _, task := range tasks {
if task.Id == id {
json.NewEncoder(w).Encode(task)
}
}
}
/*
* [ Handler ] Retreive all tasks
*/
func getTasks(w http.ResponseWriter, r *http.Request) {
log.Info("Retrieving tasks")
tasks := fetchDB()
err := json.NewEncoder(w).Encode(tasks)
if err != nil {
log.WithFields(logrus.Fields{
"error": err,
}).Error("Could not get tasks")
fmt.Fprintf(w, "Error encoding json")
}
}
/*
* [ Handler ] Update a task
* CHANGEME
*/
func updateTask(w http.ResponseWriter, r *http.Request) {
log.Info("updating task")
id := mux.Vars(r)["id"]
var updated Task
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, "Please enter data")
log.WithFields(logrus.Fields{
"body": string(body),
}).Error("did not receive data")
}
json.Unmarshal(body, &updated)
updateDB(w, id, updated)
}
/*
* [ Handler ] Delete a task using id
*/
func deleteTask(w http.ResponseWriter, r *http.Request) {
log.Info("Deleting task")
id := mux.Vars(r)["id"]
tasks := fetchDB()
for i, task := range tasks {
if task.Id == id {
tasks = append(tasks[:i], tasks[i+1:]...)
fmt.Fprintf(w, "ID(%v) has been deleted", id)
log.WithFields(logrus.Fields{
"id": id,
}).Info("Task has been deleted")
}
}
writeDB(tasks)
}
/*
*
* [ Handler ] Get the system info
*/
func getSystem(w http.ResponseWriter, r *http.Request) {
name, err := os.Hostname()
if err != nil {
// fmt.Fprintf(w, "Could not get hostname")
log.Error("Could not get hostname")
// Set status
} else {
type SystemInfo struct {
Hostname string `json:"hostname"`
}
si := SystemInfo {
Hostname: name,
}
json.NewEncoder(w).Encode(si)
}
}
/*
* [ Handler ] Home landing page
*/
func homeLink(w http.ResponseWriter, r *http.Request) {
log.Info("Hit home!")
fmt.Fprintf(w, "Welcome to TODO note server!")
}
/*
* Initialize the database
*/
func init() {
if _, err := os.Stat(filepath); err == nil {
log.Info("Found db")
} else if os.IsNotExist(err) {
f, err := os.Create(filepath)
if err != nil {
log.WithFields(logrus.Fields{
"error": err,
}).Fatal("Could not create db")
}
f.Close()
} else {
log.WithFields(logrus.Fields{
"error": err,
}).Fatal("Finding db failed")
}
}
/*
* Use Gorilla Mux to handle routes
*/
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", homeLink)
router.HandleFunc("/api/system", getSystem).Methods("GET")
router.HandleFunc("/api/create", createTask).Methods("POST")
router.HandleFunc("/api/tasks/{id}", getOneTask).Methods("GET")
router.HandleFunc("/api/tasks", getTasks).Methods("GET")
router.HandleFunc("/api/update/{id}", updateTask).Methods("PATCH")
router.HandleFunc("/api/delete/{id}", deleteTask).Methods("DELETE")
log.Fatal(http.ListenAndServe(":9000", router))
}