Skip to content

Commit

Permalink
refactor to introduce a simplistic URL router, logging, and html temp…
Browse files Browse the repository at this point in the history
…lates with a data driven table
  • Loading branch information
johnpfeiffer committed May 9, 2018
1 parent a46d229 commit c8636ee
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 4 deletions.
27 changes: 27 additions & 0 deletions hexcolors.go
@@ -0,0 +1,27 @@
package main

import (
"fmt"
"html/template"
"net/http"
)

// HexColors wraps a list of colors as hexadecimal strings
type HexColors struct {
Colors []string
}

// GetHexTemplate returns the parsed file as a template object
func GetHexTemplate() *template.Template {
return template.Must(template.ParseFiles("hexcolorstemplate.html"))
}

func hexController(w http.ResponseWriter, r *http.Request) {
colors := []string{}
for i := 255; i <= 16711680; i = i * 256 {
s := fmt.Sprintf("%06X", i)
colors = append(colors, s)
}
data := HexColors{colors}
hexTemplate.Execute(w, data)
}
16 changes: 16 additions & 0 deletions hexcolorstemplate.html
@@ -0,0 +1,16 @@
<html>
<head><style>
table, th, td {
border: 2px solid black;
}
</style></head>
<body>
<table>
{{range .Colors}}
<tr>
<td>{{.}}</td><td style="background-color: {{.}}; ">__</td>
</tr>
{{end}}
</table>
</body>
</html>
2 changes: 1 addition & 1 deletion indextemplate.go
Expand Up @@ -19,7 +19,7 @@ body{
</style>
</head>
<body>
hi
hi , try <a href="/hexcolors">hexcolors</a>
</body>
</html>
`))
Expand Down
16 changes: 13 additions & 3 deletions main.go
Expand Up @@ -4,18 +4,28 @@ import (
"log"
"net/http"
"os"
"strings"
)

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

func myHandler(w http.ResponseWriter, r *http.Request) {
indexTemplate.Execute(w, NoData{})
func myRouter(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "favicon") {
log.Println(r.URL.Path)
}
if strings.ToLower(r.URL.Path) == "/hexcolors" {
hexController(w, r)
} else {
indexTemplate.Execute(w, NoData{})
}
}

func main() {
port := getEnvOrDefault("PORT", "8080")
log.Println("Listening on port", port)
http.HandleFunc("/", myHandler)
http.HandleFunc("/", myRouter)
http.ListenAndServe(":"+port, nil)
}

Expand Down

0 comments on commit c8636ee

Please sign in to comment.