meeting/main.go

89 lines
2.1 KiB
Go

package main
import (
"context"
"fmt"
"github.com/kordondev/meeting/throttling"
"net/http"
"slices"
"time"
)
const burstLimit = 2
func main() {
ctx := context.Background()
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) {
ctx, cancel := context.WithCancel(ctx)
throttle := throttling.CreateThrottle(ctx, burstLimit)
a := throttleWithCancel{
throttle: throttle,
cancel: cancel,
}
con := context.WithValue(ctx, "throttle", a)
tryResult(ctx, w, r, throttles, calledLastHour)
})
err := http.ListenAndServe(":3333", nil)
if err != nil {
fmt.Printf("http.ListenAndServe() failed with %s\n", err)
}
}
type throttleWithCancel struct {
throttle <-chan time.Time
cancel context.CancelFunc
}
func serveIndexFile(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index-with-text.html")
}
func serveInputFile(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.RemoteAddr)
http.ServeFile(w, r, "static/input.txt")
}
func tryResult(ctx context.Context, 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(ctx, burstLimit)
throttles[clientIP] = throttle
}
payload := throttling.Payload{
R: r,
W: w,
ClientResult: clientResult,
}
throttling.CallFunction(ctx, &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")
}