forked from katzien/go-structure-examples
/
handler.go
52 lines (43 loc) · 1.4 KB
/
handler.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
package beers
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/julienschmidt/httprouter"
"github.com/katzien/go-structure-examples/modular/storage"
)
// GetBeers returns the cellar
func GetBeers(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
cellar := storage.DB.FindBeers()
json.NewEncoder(w).Encode(cellar)
}
// GetBeer returns a beer from the cellar
func GetBeer(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
ID, err := strconv.Atoi(ps.ByName("id"))
if err != nil {
http.Error(w, fmt.Sprintf("%s is not a valid Beer ID, it must be a number.", ps.ByName("id")), http.StatusBadRequest)
return
}
cellar, _ := storage.DB.FindBeer(Beer{ID: ID})
if len(cellar) == 1 {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(cellar[0])
return
}
http.Error(w, "The beer you requested does not exist.", http.StatusNotFound)
}
// AddBeer adds a new beer to the cellar
func AddBeer(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
decoder := json.NewDecoder(r.Body)
var newBeer Beer
err := decoder.Decode(&newBeer)
if err != nil {
http.Error(w, "Bad beer - this will be a HTTP status code soon!", http.StatusBadRequest)
return
}
storage.DB.SaveBeer(newBeer)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode("New beer added.")
}