package main

import (
	"fmt"
	"gogs.inhome.blapointe.com/local/args"
	"log"
	"net/http"

	"golang.org/x/time/rate"
)

func main() {
	as := args.NewArgSet()

	as.Append(args.INT, "port", "port to listen on", 8080)
	as.Append(args.STRING, "root", "root dir to serve", "./public")
	as.Append(args.INT, "rps", "rate limit in requests per second", 3)

	if err := as.Parse(); err != nil {
		panic(err)
	}

	log.Printf("listening on %v to serve %s at %d rps", as.GetInt("port"), as.GetString("root"), as.GetInt("rps"))

	s := http.FileServer(http.Dir(as.GetString("root")))
	limiter := rate.NewLimiter(rate.Limit(as.GetInt("rps")), as.GetInt("rps"))
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", as.GetInt("port")), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if err := limiter.Wait(r.Context()); err != nil {
			log.Println("rate limited:", err)
			return
		}
		s.ServeHTTP(w, r)
	})))
}
