-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
60 lines (50 loc) · 1.54 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
package main
import (
"html/template"
"log"
"net/http"
)
type AssetCreate struct {
Ticker string `form:"ticker"`
Quantity int `form:"quantity"`
Price int `form:"price"`
}
func (application *application) home(w http.ResponseWriter, r *http.Request) {
pattern := []string{
"./ui/html/base.tmpl.html",
"./ui/html/pages/home.tmpl.html",
}
ts, err := template.ParseFiles(pattern...)
if err != nil {
log.Print(err.Error())
http.Error(w, "Internal Server error", http.StatusInternalServerError)
return
}
err = ts.ExecuteTemplate(w, "base", &TemplateData{StockAssets: application.stockRepo.stockAssets})
if err != nil {
log.Print(err.Error())
http.Error(w, "Internal Server error", http.StatusInternalServerError)
}
}
func (application *application) assetsCreate(w http.ResponseWriter, r *http.Request) {
var form AssetCreate
err := application.decodeForm(r, &form)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
}
if !isNotEmpty(form.Ticker) || !isPositive(form.Quantity) || !isPositive(form.Price) {
http.Error(w, "Bad Request", http.StatusBadRequest)
}
asset := application.stockRepo.insert(form.Ticker, form.Quantity, form.Price)
ts, err := template.ParseFiles("./ui/html/partials/asset-row.tmpl.html")
if err != nil {
log.Print(err.Error())
http.Error(w, "Internal Server error", http.StatusInternalServerError)
return
}
err = ts.ExecuteTemplate(w, "asset-row", &asset)
if err != nil {
log.Print(err.Error())
http.Error(w, "Internal Server error", http.StatusInternalServerError)
}
}