forked from ssproessig/go-webservice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest_api.go
68 lines (56 loc) · 1.23 KB
/
rest_api.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
package main
import (
"net/http"
"encoding/json"
"log"
"github.com/gorilla/mux"
)
type Todo struct {
Id string `json:"id"`
Title string `json:"title"`
}
var todos []Todo
func GetTodos(w http.ResponseWriter, _ *http.Request) {
json.NewEncoder(w).Encode(todos)
}
func GetTodo(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, item := range todos {
if item.Id == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
w.WriteHeader(404)
}
func AddReplaceTodo(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var newTodo Todo
_ = json.NewDecoder(r.Body).Decode(&newTodo)
newTodo.Id = params["id"]
for i := 0; i < len(todos); i++ {
todo := &todos[i]
if todo.Id == params["id"] {
*todo = newTodo
log.Print("Replaced Todo: ", newTodo)
todoChanged <- newTodo
return
}
}
todos = append(todos, newTodo)
log.Print("Added Todo: ", newTodo)
todoChanged <- newTodo
w.WriteHeader(201)
}
func DeleteTodo(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for i := 0; i < len(todos); i++ {
todo := &todos[i]
if todo.Id == params["id"] {
log.Print("Deleting Todo: ", todo)
todos = append(todos[:i], todos[i+1:]...)
return
}
}
w.WriteHeader(404)
}