Skip to content

Commit c8636ee

Browse files
committed
refactor to introduce a simplistic URL router, logging, and html templates with a data driven table
1 parent a46d229 commit c8636ee

File tree

4 files changed

+57
-4
lines changed

4 files changed

+57
-4
lines changed

hexcolors.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"html/template"
6+
"net/http"
7+
)
8+
9+
// HexColors wraps a list of colors as hexadecimal strings
10+
type HexColors struct {
11+
Colors []string
12+
}
13+
14+
// GetHexTemplate returns the parsed file as a template object
15+
func GetHexTemplate() *template.Template {
16+
return template.Must(template.ParseFiles("hexcolorstemplate.html"))
17+
}
18+
19+
func hexController(w http.ResponseWriter, r *http.Request) {
20+
colors := []string{}
21+
for i := 255; i <= 16711680; i = i * 256 {
22+
s := fmt.Sprintf("%06X", i)
23+
colors = append(colors, s)
24+
}
25+
data := HexColors{colors}
26+
hexTemplate.Execute(w, data)
27+
}

hexcolorstemplate.html

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<html>
2+
<head><style>
3+
table, th, td {
4+
border: 2px solid black;
5+
}
6+
</style></head>
7+
<body>
8+
<table>
9+
{{range .Colors}}
10+
<tr>
11+
<td>{{.}}</td><td style="background-color: {{.}}; ">__</td>
12+
</tr>
13+
{{end}}
14+
</table>
15+
</body>
16+
</html>

indextemplate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ body{
1919
</style>
2020
</head>
2121
<body>
22-
hi
22+
hi , try <a href="/hexcolors">hexcolors</a>
2323
</body>
2424
</html>
2525
`))

main.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,28 @@ import (
44
"log"
55
"net/http"
66
"os"
7+
"strings"
78
)
89

10+
// TODO: globals are evil - there is a better way
911
var indexTemplate = GetIndexTemplate()
12+
var hexTemplate = GetHexTemplate()
1013

11-
func myHandler(w http.ResponseWriter, r *http.Request) {
12-
indexTemplate.Execute(w, NoData{})
14+
func myRouter(w http.ResponseWriter, r *http.Request) {
15+
if !strings.Contains(r.URL.Path, "favicon") {
16+
log.Println(r.URL.Path)
17+
}
18+
if strings.ToLower(r.URL.Path) == "/hexcolors" {
19+
hexController(w, r)
20+
} else {
21+
indexTemplate.Execute(w, NoData{})
22+
}
1323
}
1424

1525
func main() {
1626
port := getEnvOrDefault("PORT", "8080")
1727
log.Println("Listening on port", port)
18-
http.HandleFunc("/", myHandler)
28+
http.HandleFunc("/", myRouter)
1929
http.ListenAndServe(":"+port, nil)
2030
}
2131

0 commit comments

Comments
 (0)