-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
84 lines (57 loc) · 1.39 KB
/
handlers.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
func HandlerHome(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "holaa")
}
func GetAllArticles(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(w)
err := encoder.Encode(Articles)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
}
}
func GetSingleArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
for _, article := range Articles {
if article.Id == key {
json.NewEncoder(w).Encode(article)
return
}
}
w.WriteHeader(http.StatusNotFound)
}
func PostArticle(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadAll(r.Body)
var article Article
json.Unmarshal(data, &article)
Articles = append(Articles, article)
json.NewEncoder(w).Encode(article)
}
func UpdateArticle(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadAll(r.Body)
var article Article
json.Unmarshal(data, &article)
for _, art := range Articles {
if art.Id == article.Id {
art = article
json.NewEncoder(w).Encode(article)
return
}
}
w.WriteHeader(http.StatusNotFound)
}
func DeleteArticle(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
for index, article := range Articles {
if article.Id == id {
Articles = append(Articles[:index], Articles[index+1:]...)
}
}
}