package main

import (
	"flag"
	"log"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"time"
)

type myConfig struct {
	MyURL  string
	MySock string
}

func main() {
	var c myConfig

	flag.StringVar(&c.MyURL, "url", "", "URL to proxy to")
	flag.StringVar(&c.MySock, "unix", "", "Unix socket to listen on")

	flag.Parse()

	if c.MySock == "" {
		log.Fatal("sock argument required")
	}
	rpURL, err := url.Parse("http://127.0.0.1:8080")
	if err != nil {
		log.Fatal(err)
	}

	if err := os.RemoveAll(c.MySock); err != nil {
		log.Fatal(err)
	}

	frontendProxy := httputil.NewSingleHostReverseProxy(rpURL)

	srv := &http.Server{
		ReadTimeout:       2 * time.Second,
		WriteTimeout:      3 * time.Second,
		IdleTimeout:       30 * time.Second,
		ReadHeaderTimeout: 20 * time.Second,
		Handler:           frontendProxy,
	}

	unixListener, err := net.Listen("unix", c.MySock)

	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(srv.Serve(unixListener))
}
