-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathbird_handlers.go
56 lines (45 loc) · 1.41 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
54
55
56
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Bird struct {
Species string `json:"species"`
Description string `json:"description"`
}
var birds []Bird
func getBirdHandler(w http.ResponseWriter, r *http.Request) {
//Convert the "birds" variable to json
birdListBytes, err := json.Marshal(birds)
// If there is an error, print it to the console, and return a server
// error response to the user
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
// If all goes well, write the JSON list of birds to the response
w.Write(birdListBytes)
}
func createBirdHandler(w http.ResponseWriter, r *http.Request) {
// Create a new instance of Bird
bird := Bird{}
// We send all our data as HTML form data
// the `ParseForm` method of the request, parses the
// form values
err := r.ParseForm()
// In case of any error, we respond with an error to the user
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
// Get the information about the bird from the form info
bird.Species = r.Form.Get("species")
bird.Description = r.Form.Get("description")
// Append our existing list of birds with a new entry
birds = append(birds, bird)
//Finally, we redirect the user to the original HTMl page (located at `/assets/`)
http.Redirect(w, r, "/assets/", http.StatusFound)
}