forked from sohamkamani/blog_example__go_web_db
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbird_handlers.go
53 lines (42 loc) · 1.14 KB
/
bird_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
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Bird struct {
Species string `json:"species"`
Description string `json:"description"`
}
func getBirdHandler(w http.ResponseWriter, r *http.Request) {
/*
The list of birds is now taken from the store instead of the package level variable we had earlier
*/
birds, err := store.GetBirds()
// Everything else is the same as before
birdListBytes, err := json.Marshal(birds)
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(birdListBytes)
}
func createBirdHandler(w http.ResponseWriter, r *http.Request) {
bird := Bird{}
err := r.ParseForm()
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
bird.Species = r.Form.Get("species")
bird.Description = r.Form.Get("description")
// The only change we made here is to use the `CreateBird` method instead of
// appending to the `bird` variable like we did earlier
err = store.CreateBird(&bird)
if err != nil {
fmt.Println(err)
}
http.Redirect(w, r, "/assets/", http.StatusFound)
}