Skip to content
Snippets Groups Projects
main.go 1.39 KiB
Newer Older
timbastin's avatar
timbastin committed
package main

import (
	"encoding/hex"
	"fmt"
	"html/template"
	"log"
	"net"
timbastin's avatar
timbastin committed
	"net/http"
	"os"
)

type ViewData struct {
timbastin's avatar
timbastin committed
	Hostname        string
	IpAddresses     []string
timbastin's avatar
timbastin committed
	BackgroundColor string
	AmountCalled    int
var amountCalled = 0

timbastin's avatar
timbastin committed
func webHandlerFactory(tmpl *template.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
timbastin's avatar
timbastin committed
		if r.URL.Path != "/" {
			w.WriteHeader(404)
			return // 404
		}
		amountCalled++
timbastin's avatar
timbastin committed
		log.Println("request received")
timbastin's avatar
timbastin committed
		hostname, err := os.Hostname()
		addrs, err := net.InterfaceAddrs()
		ipAddresses := make([]string, len(addrs))
		for i, addr := range addrs {
			ipAddresses[i] = addr.String()
		}
timbastin's avatar
timbastin committed
		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, ViewData{
timbastin's avatar
timbastin committed
			Hostname:        hostname,
			BackgroundColor: fmt.Sprintf("#%s", hexStr),
			AmountCalled:    amountCalled,
			IpAddresses:     ipAddresses,
timbastin's avatar
timbastin committed
		})

		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")
timbastin's avatar
timbastin committed
	http.ListenAndServe(":80", nil)