package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"runtime"

	"github.com/kr/pretty"
	"go.uber.org/atomic"
)

var (
	port = flag.String("port", "9090", "HTTP port to listen on")

	hits *atomic.Int64
)

func main() {
	flag.Parse()
	hits = atomic.NewInt64(0)
	http.ListenAndServe(":"+*port, http.HandlerFunc(handle))
}

func handle(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Route is go!")
	fmt.Fprintf(w, "%s\n", pretty.Sprintf("%s", r.Header))
	hn, _ := os.Hostname()
	fmt.Fprintf(w, "Served by %s running %s\n", hn, runtime.GOOS)
	fmt.Fprintf(w, "Hit count: %d", hits.Inc())

	ip := r.Header.Get("X-Remote-Ip")
	if ip != "" {
		log.Printf("Hit from %s: %s", ip, r.RequestURI)
	}
}
