package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	var bind = flag.String("bind", ":8081", "Bind port/socket")
	flag.Parse()

	// Prepare graceful shutdown
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
	signal.Notify(interrupt, os.Interrupt, syscall.SIGINT)

	srv := &http.Server{
		Addr: *bind,
	}

	log.Println("Registering handlers...")
	mux := http.NewServeMux()
	mux.HandleFunc("/register", register)
	http.HandleFunc("/", mux.ServeHTTP)

	// Serve content
	go func() {
		log.Fatal(srv.ListenAndServe())
	}()
	log.Println(fmt.Sprintf("Ready, listening on %s", *bind))

	// Wait shutdown signal
	<-interrupt

	log.Print("The service is shutting down...")
	srv.Shutdown(context.Background())
	log.Println("done")
}
