-
Notifications
You must be signed in to change notification settings - Fork 3
/
citiesHandlers.go
115 lines (94 loc) · 1.83 KB
/
citiesHandlers.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"strings"
"github.com/k0kubun/pp"
)
func newCity(w http.ResponseWriter, r *http.Request, countryId int) {
var tmplData struct {
Country country
CancelPath string
}
c := country{Id: countryId}
err := c.read()
if err != nil {
log.Println(err)
httpGenericErr(w)
return
}
tmplData.Country = c
tmplData.CancelPath = strings.Replace(r.URL.Path, "/new", "", -1)
renderHTML(w, tmplData, "cities/new")
}
func createCity(w http.ResponseWriter, r *http.Request) {
strCountryId := r.FormValue("countryId")
name := r.FormValue("name")
countryId, err := strconv.Atoi(strCountryId)
if err != nil {
log.Println(err)
httpGenericErr(w)
return
}
c := &city{
Country: country{Id: countryId},
Name: name,
}
err = c.create()
if err != nil {
log.Println(err)
httpGenericErr(w)
return
}
}
func showCity(w http.ResponseWriter, r *http.Request, id int) {
c := &city{Id: id}
err := c.read()
if err != nil {
log.Println(err)
httpGenericErr(w)
return
}
if isAPIPath(r.URL.Path) {
renderJSON(w, c)
} else {
renderHTML(w, c, "cities/show")
}
}
func editCity(w http.ResponseWriter, r *http.Request, id int) {
c := &city{Id: id}
pp.Println("c =", c)
err := c.read()
if err != nil {
fmt.Println(err)
httpGenericErr(w)
return
}
pp.Println("c =", c)
if isAPIPath(r.URL.Path) {
renderJSON(w, c)
} else {
renderHTML(w, c, "cities/edit")
}
}
func updateCity(w http.ResponseWriter, r *http.Request, id int) {
name := r.FormValue("name")
c := &city{Id: id, Name: name}
err := c.update()
if err != nil {
fmt.Println("updateCity:", err)
httpGenericErr(w)
return
}
}
func deleteCity(w http.ResponseWriter, r *http.Request, id int) {
c := &city{Id: id}
err := c.delete()
if err != nil {
fmt.Println(err)
httpGenericErr(w)
return
}
}