-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
78 lines (64 loc) · 1.7 KB
/
app.go
File metadata and controls
78 lines (64 loc) · 1.7 KB
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
)
func handleRequests() {
port := os.Getenv("PORT");
if port == "" {
port = "8080"
}
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", hello)
myRouter.HandleFunc("/status", status)
myRouter.HandleFunc("/categories", categoryList)
myRouter.HandleFunc("/category/{id}", categoryView)
myRouter.HandleFunc("/category", categoryCreate).Methods("POST")
fmt.Println("Starting up on " + port)
log.Fatal(http.ListenAndServe(":" + port, myRouter))
}
func main() {
Categories = []Category{
{Id: "1", Title: "Food", Description: "First category"},
{Id: "2", Title: "Gas", Description: "Fuel for our car"},
}
handleRequests()
}
type Category struct {
Id string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
}
var Categories []Category
func categoryList(w http.ResponseWriter, req *http.Request) {
json.NewEncoder(w).Encode(Categories)
}
func categoryView(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
key := vars["id"]
for _, category := range Categories {
if category.Id == key {
json.NewEncoder(w).Encode(category)
}
}
}
func categoryCreate(w http.ResponseWriter, req *http.Request) {
reqBody, _ := ioutil.ReadAll(req.Body)
var category Category
json.Unmarshal(reqBody, &category)
// update our global Articles array to include
// our new Article
Categories = append(Categories, category)
json.NewEncoder(w).Encode(Categories)
}
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "Hello world!")
}
func status(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "STATUS: OK!")
}