-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (53 loc) · 1.41 KB
/
main.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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Item struct {
ID string `json:"id,omitempty"`
name string `json:"name,omitempty"`
}
var items []Item
func GetItems(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(items)
}
func GetItem(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, item := range items {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Item{})
}
func CreateItem(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var item Item
_ = json.NewDecoder(r.Body).Decode(&item)
item.ID = params["id"]
items = append(items, item)
json.NewEncoder(w).Encode(items)
}
func DeleteItem(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range items {
if item.ID == params["id"] {
items = append(items[:index], items[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(items)
}
func main() {
router := mux.NewRouter()
items = append(items, Item{ID: "1", name: "Item 1"})
items = append(items, Item{ID: "2", name: "Item 2"})
router.HandleFunc("/items", GetItems).Methods("GET")
router.HandleFunc("/items/{id}", GetItem).Methods("GET")
router.HandleFunc("/items/{id}", CreateItem).Methods("POST")
router.HandleFunc("/items/{id}", DeleteItem).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8000", router))
}