forked from ardanlabs/gotraining
/
handler.go
93 lines (73 loc) · 2.13 KB
/
handler.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
package service
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/ardanlabs/gotraining/topics/profiling/project/search"
"github.com/pborman/uuid"
)
// handler handles the search route processing.
func handler(w http.ResponseWriter, r *http.Request) {
uid := uuid.New()
log.Printf("%s : handler : Started : Method[%s] URL[%s]\n", uid, r.Method, r.URL)
// Capture all the form values.
fv, options := formValues(r)
log.Printf("%s : handler : Info : options[%#v]\n", uid, options)
// If this is a post, perform a search.
var results []search.Result
if r.Method == "POST" && options.Term != "" {
results = search.Submit(uid, options)
}
// Render the search page.
markup := render(fv, results)
// Write the final markup as the response.
fmt.Fprint(w, string(markup))
log.Printf("%s : handler : Completed\n", uid)
}
// 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["term"] = r.FormValue("term")
options.Term = r.FormValue("term")
if r.FormValue("cnn") == "on" {
fv["cnn"] = "checked"
options.CNN = true
} else {
fv["cnn"] = ""
}
if r.FormValue("nyt") == "on" {
fv["nyt"] = "checked"
options.NYT = true
} else {
fv["nyt"] = ""
}
if r.FormValue("bbc") == "on" {
fv["bbc"] = "checked"
options.BBC = true
} else {
fv["bbc"] = ""
}
if r.FormValue("first") == "on" {
fv["first"] = "checked"
options.First = true
} else {
fv["first"] = ""
}
return fv, options
}
// render generates the HTML response for this route.
func render(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 search template.
markup := executeTemplate("search", fv)
// Generate the final markup with the layout template.
vars := map[string]interface{}{"LayoutContent": template.HTML(string(markup))}
return executeTemplate("layout", vars)
}