main.go 1.39 KB
Newer Older
Syed Areeb Hussain's avatar
Syed Areeb Hussain committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main

import (
	"encoding/hex"
	"fmt"
	"html/template"
	"log"
	"net"
	"net/http"
	"os"
)

type ViewData 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) {
		if r.URL.Path != "/" {
			w.WriteHeader(404)
			return // 404
		}
		amountCalled++
		log.Println("request received")
		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, ViewData{
			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(":80", nil)
}