Permalink
Browse files

refactor to introduce a simplistic URL router, logging, and html temp…

…lates with a data driven table
  • Loading branch information...
johnpfeiffer committed May 9, 2018
1 parent a46d229 commit c8636ee4f54ff95d4a804a152954874f5c23b682
Showing with 57 additions and 4 deletions.
  1. +27 −0 hexcolors.go
  2. +16 −0 hexcolorstemplate.html
  3. +1 −1 indextemplate.go
  4. +13 −3 main.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)
}
@@ -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>
@@ -19,7 +19,7 @@ body{
</style>
</head>
<body>
hi
hi , try <a href="/hexcolors">hexcolors</a>
</body>
</html>
`))
16 main.go
@@ -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)
}

0 comments on commit c8636ee

Please sign in to comment.