forked from ackvf/golang-brno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
56 lines (44 loc) · 1.03 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
// now we NEED to do `go build` and then run the executable
// `go run` can only run single files and doesn't resolve those linked
package main
import (
"encoding/json"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", rootHandler)
mux.HandleFunc("/todo", todoHandler)
http.ListenAndServe(":8080", mux)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello server3"))
}
func todoHandler(w http.ResponseWriter, r *http.Request) {
// jin
// negroni
// gorilla mux
switch r.Method {
case "GET":
todo := GetAll() // GetTodo is found automatically from todo.go as it is in same package
result, err := json.Marshal(todo)
if err != nil {
panic(err)
}
w.WriteHeader(http.StatusOK)
w.Write(result)
case "POST":
todo := Todo{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&todo)
if err != nil {
panic(err)
}
SaveTodo(todo)
w.WriteHeader(http.StatusOK)
case "PUT":
w.Write([]byte("PUT"))
case "DELETE":
w.Write([]byte("DELETE"))
}
}