forked from sbotman/go-training
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.go
92 lines (73 loc) · 2.25 KB
/
index.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
// All material is licensed under the GNU Free Documentation License
// Package service : index maintains the support for the home page.
package service
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/disney/go-training/web_app/sample/search"
)
// index handles the home page route processing.
func index(w http.ResponseWriter, r *http.Request) {
log.Printf("service : index : Started : Method[%s]\n", r.Method)
// Capture all the form values.
fv, options := formValues(r)
log.Printf("service : index : Info : options[%#v]\n", options)
// If this is a post, perform a search.
var results []search.Result
if r.Method == "POST" && options.SearchTerm != "" {
results = search.Submit(options)
}
// Render the index page.
markup := renderIndex(fv, results)
// Write the final markup as the response.
fmt.Fprint(w, string(markup))
log.Println("service : index : Completed")
}
// formValues extracts the form data.
func formValues(r *http.Request) (map[string]interface{}, *search.Options) {
fv := make(map[string]interface{})
var options search.Options
fv["searchterm"] = r.FormValue("searchterm")
options.SearchTerm = r.FormValue("searchterm")
if r.FormValue("google") == "on" {
fv["google"] = "checked"
options.Google = true
} else {
fv["google"] = ""
}
if r.FormValue("bing") == "on" {
fv["bing"] = "checked"
options.Bing = true
} else {
fv["bing"] = ""
}
if r.FormValue("blekko") == "on" {
fv["blekko"] = "checked"
options.Blekko = true
} else {
fv["blekko"] = ""
}
if r.FormValue("first") == "on" {
fv["first"] = "checked"
options.First = true
} else {
fv["first"] = ""
}
return fv, &options
}
// renderIndex generates the HTML response for this route.
func renderIndex(fv map[string]interface{}, results []search.Result) []byte {
// Generate the markup for the results template.
if results != nil {
vars := map[string]interface{}{"Items": results}
markup := executeTemplate("results", vars)
fv["Results"] = template.HTML(string(markup))
}
// Generate the markup for the index template.
markup := executeTemplate("index", fv)
// Generate the final markup with the layout template.
vars := map[string]interface{}{"LayoutContent": template.HTML(string(markup))}
return executeTemplate("layout", vars)
}