package main import ( "encoding/hex" "fmt" "html/template" "log" "net" "net/http" "os" ) type ViewModel struct { Hostname string IpAddresses []string BackgroundColor string AmountCalled int } var amountCalled = 0 func webHandlerFactory(tmpl *template.Template) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { amountCalled++ hostname, err := os.Hostname() addrs, err := net.InterfaceAddrs() ipAddresses := make([]string, len(addrs)) for i, addr := range addrs { ipAddresses[i] = addr.String() } if err != nil { log.Println(err) http.Error(w, err.Error(), 500) return } hexStr := hex.EncodeToString([]byte(hostname)) // make sure, that the hexStr is not longer than 6 digits if len(hexStr) > 6 { hexStr = hexStr[:6] } err = tmpl.Execute(w, ViewModel{ Hostname: hostname, BackgroundColor: fmt.Sprintf("#%s", hexStr), AmountCalled: amountCalled, IpAddresses: ipAddresses, }) if err != nil { http.Error(w, err.Error(), 500) log.Println(err.Error()) } } } func main() { // parse the template tmpl, err := template.ParseFiles("index.gohtml") if err != nil { panic(err) } http.HandleFunc("/", webHandlerFactory(tmpl)) log.Println("started web server") http.ListenAndServe(":3000", nil) }