forked from dockersamples/single-dev-env
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (61 loc) · 1.88 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Article struct {
Id string `json:"id"`
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
var Articles []Article
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Homepage!")
fmt.Println("Endpoint Hit: homepage")
}
func returnAllArticles(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: returnAllArticles")
json.NewEncoder(w).Encode(Articles)
}
func returnSingleArticle(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)
}
}
}
func createNewArticle(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: createNewArticle")
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))
fmt.Printf("Data: %v\n", string(reqBody))
}
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
fmt.Println("GOT ATTEMPT")
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
myRouter.HandleFunc("/articles", returnAllArticles)
myRouter.HandleFunc("/article/{id}", returnSingleArticle)
log.Fatal(http.ListenAndServe(":10000", myRouter))
}
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 2", Content: "Article Content 2"},
Article{Id: "3", Title: "Hello 3", Desc: "Article Description 3", Content: "Article Content 3"},
}
handleRequests()
}