This commit is contained in:
Arne Maier 2024-11-11 21:52:33 +01:00
parent 47ed047f7e
commit 82790e260d
1 changed files with 9 additions and 9 deletions

18
main.go
View File

@ -5,7 +5,6 @@ import (
"fmt"
"github.com/kordondev/meeting/throttling"
"net/http"
"slices"
"time"
)
@ -13,8 +12,7 @@ const burstLimit = 2
func main() {
ctx := context.Background()
throttles := make(map[string]context.Context)
calledLastHour := make([]string, 0)
throttles := make(map[string]context.Context) // use sync map
http.HandleFunc("/", serveIndexFile)
http.HandleFunc("/input.txt", serveInputFile)
@ -30,9 +28,14 @@ func main() {
}
cctxV = context.WithValue(ctx, "throttle", a)
throttles[r.RemoteAddr] = cctxV
go func() {
time.Sleep(time.Minute * 20)
delete(throttles, r.RemoteAddr)
cancel()
}()
}
tryResult(cctxV, w, r, calledLastHour)
tryResult(cctxV, w, r)
})
err := http.ListenAndServe(":3333", nil)
@ -55,13 +58,10 @@ func serveInputFile(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/input.txt")
}
func tryResult(ctx context.Context, w http.ResponseWriter, r *http.Request, calledLastHour []string) {
func tryResult(ctx context.Context, w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
clientResult := r.URL.Query().Get("result")
fmt.Println(clientIP, clientResult)
if !slices.Contains(calledLastHour, clientIP) {
calledLastHour = append(calledLastHour, clientIP)
}
fmt.Println(clientIP, "called with:", clientResult)
throttle := ctx.Value("throttle").(throttleWithCancel).throttle
payload := throttling.Payload{
R: r,