-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog-api.go
99 lines (85 loc) · 2.52 KB
/
blog-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
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/gorilla/mux"
)
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcom to Home Page")
fmt.Println("Endpoint Hit: homePage")
}
func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
//fmt.Fprintf(w, "Key: "+key)
for _, article := range Articles {
if article.Id == key {
json.NewEncoder(w).Encode(article)
}
}
}
func createNewArticle(w http.ResponseWriter, r *http.Request) {
reqBody, _ := ioutil.ReadAll(r.Body)
var article Article
json.Unmarshal(reqBody, &article)
Articles = append(Articles, article)
json.NewEncoder(w).Encode(article)
//fmt.Fprintf(w, "%+v", string(reqBody))
}
func deleteArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
for index, article := range Articles {
if article.Id == id {
Articles = append(Articles[:index], Articles[index+1:]...)
}
}
}
func updateArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
for index, article := range Articles {
if article.Id == id {
Articles = append(Articles[:index], Articles[index+1:]...)
}
}
var updatedArticle Article
json.NewDecoder(r.Body).Decode(&updatedArticle)
Articles = append(Articles, updatedArticle)
json.NewEncoder(w).Encode(updatedArticle)
return
}
func handleRequest() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/articles", returnAllArticles).Methods("GET")
myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
myRouter.HandleFunc("/article/{id}", updateArticle).Methods("POST")
myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("DELETE")
myRouter.HandleFunc("/article/{id}", returnSingleArticle)
log.Fatal(http.ListenAndServe(":10000", myRouter))
}
//Article is for struct
type Article struct {
Id string `json:"Id"`
Title string `json:"Title"`
Desc string `json:"Desc"`
Content string `json:"Content"`
}
//Articles is for an Array
var Articles []Article
func returnAllArticles(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: returnAllArticles")
json.NewEncoder(w).Encode(Articles)
}
func main() {
fmt.Println("Rest API v2.0 - Mux Routers")
Articles = []Article{
Article{Id: "1", Title: "Hello", Desc: "Article Description", Content: "Article Content"},
Article{Id: "2", Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
}
handleRequest()
}