-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect.go
82 lines (65 loc) · 2.11 KB
/
select.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
package main
import (
"net/http"
"log"
"html/template"
)
type RadioButton struct {
Name string
Value string
IsDisabled bool
IsChecked bool
Text string
}
type PageVariables struct {
PageTitle string
PageRadioButtons []RadioButton
Answer string
}
func main() {
http.HandleFunc("/", DisplayRadioButtons)
http.HandleFunc("/selected", UserSelected)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func DisplayRadioButtons(w http.ResponseWriter, r *http.Request){
// Display some radio buttons to the user
Title := "Which do you prefer?"
MyRadioButtons := []RadioButton{
RadioButton{"animalselect", "cats", false, false, "Cats"},
RadioButton{"animalselect", "dogs", false, false, "Dogs"},
}
MyPageVariables := PageVariables{
PageTitle: Title,
PageRadioButtons : MyRadioButtons,
}
t, err := template.ParseFiles("select.html") //parse the html file homepage.html
if err != nil { // if there is an error
log.Print("template parsing error: ", err) // log it
}
err = t.Execute(w, MyPageVariables) //execute the template and pass it the HomePageVars struct to fill in the gaps
if err != nil { // if there is an error
log.Print("template executing error: ", err) //log it
}
}
func UserSelected(w http.ResponseWriter, r *http.Request){
r.ParseForm()
// r.Form is now either
// map[animalselect:[cats]] OR
// map[animalselect:[dogs]]
// so get the animal which has been selected
youranimal := r.Form.Get("animalselect")
Title := "Your preferred animal"
MyPageVariables := PageVariables{
PageTitle: Title,
Answer : youranimal,
}
// generate page by passing page variables into template
t, err := template.ParseFiles("select.html") //parse the html file homepage.html
if err != nil { // if there is an error
log.Print("template parsing error: ", err) // log it
}
err = t.Execute(w, MyPageVariables) //execute the template and pass it the HomePageVars struct to fill in the gaps
if err != nil { // if there is an error
log.Print("template executing error: ", err) //log it
}
}