package main import ( "context" "fmt" "github.com/kordondev/meeting/throttling" "net/http" "slices" "time" ) const burstLimit = 2 func main() { throttles := make(map[string]<-chan time.Time) calledLastHour := make([]string, 0) http.HandleFunc("/", serveIndexFile) http.HandleFunc("/input.txt", serveInputFile) http.HandleFunc("/result", func(w http.ResponseWriter, r *http.Request) { tryResult(w, r, throttles, calledLastHour) }) err := http.ListenAndServe(":3333", nil) if err != nil { fmt.Printf("http.ListenAndServe() failed with %s\n", err) } } func serveIndexFile(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "static/index.html") } func serveInputFile(w http.ResponseWriter, r *http.Request) { fmt.Println(r.RemoteAddr) http.ServeFile(w, r, "static/input.txt") } func tryResult(w http.ResponseWriter, r *http.Request, throttles map[string]<-chan time.Time, calledLastHour []string) { clientIP := r.RemoteAddr clientResult := r.URL.Query().Get("result") fmt.Println(clientIP, clientResult) if slices.Contains(calledLastHour, clientIP) { calledLastHour = append(calledLastHour, clientIP) } throttle, ok := throttles[clientIP] if !ok { fmt.Println("Creating new throttle") throttle = throttling.CreateThrottle(r.Context(), burstLimit) throttles[clientIP] = throttle } payload := throttling.Payload{ R: r, W: w, ClientResult: clientResult, } throttling.CallFunction(context.TODO(), &CheckResult{}, &payload, throttle) } type CheckResult struct { } func (*CheckResult) Call(payload *throttling.Payload) { w := payload.W r := payload.R fmt.Println("Serve now") if payload.ClientResult == "12" { http.ServeFile(w, r, "static/success.html") } http.ServeFile(w, r, "static/fail.html") }