-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
94 lines (83 loc) · 2.27 KB
/
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/mt2d2/purchases/dal"
)
func writeJSON(w http.ResponseWriter, val interface{}) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(val); err != nil {
log.Printf("error encoding json response: %s", err)
}
}
func (app *app) handlePurchases(w http.ResponseWriter, req *http.Request) {
purchases, err := dal.GetPurchasesAfterLastMarker(app.db)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, purchases)
}
func (app *app) handlePurchase(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id, ok := vars["id"]
if !ok {
http.Error(w, "id feld is missing", http.StatusInternalServerError)
return
}
byID, err := strconv.ParseUint(id, 0, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
purchase, err := dal.GetPurchase(app.db, byID)
if err != nil {
http.Error(w, "no such record", http.StatusNotFound)
return
}
writeJSON(w, purchase)
}
func (app *app) handleDelete(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id, ok := vars["id"]
if !ok {
http.Error(w, "id feld is missing", http.StatusInternalServerError)
return
}
byID, err := strconv.ParseUint(id, 0, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = dal.DeletePurchase(app.db, byID)
if err != nil {
http.Error(w, "no such record", http.StatusNotFound)
return
}
}
func (app *app) handleAddPurchase(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var newPurchase dal.Purchase
err := decoder.Decode(&newPurchase)
if err != nil {
log.Printf("could not decode json: %s", err)
http.Error(w, "could not decode json", http.StatusInternalServerError)
return
}
newPurchase.ID = 0
newPurchase.TimeBought = time.Now()
ok, errs := dal.ValidatePurchase(&newPurchase)
if !ok || len(errs) != 0 {
http.Error(w, "could not validate purchase", http.StatusInternalServerError)
return
}
err = dal.AddPurchase(app.db, &newPurchase)
if err != nil {
http.Error(w, "could not save purchase", http.StatusInternalServerError)
return
}
}