Add throttle to context
This commit is contained in:
parent
ac5837e26a
commit
47ed047f7e
29
main.go
29
main.go
|
|
@ -13,22 +13,26 @@ const burstLimit = 2
|
|||
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
throttles := make(map[string]<-chan time.Time)
|
||||
throttles := make(map[string]context.Context)
|
||||
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,
|
||||
cctxV, ok := throttles[r.RemoteAddr]
|
||||
if !ok {
|
||||
cctx, cancel := context.WithCancel(ctx)
|
||||
throttle := throttling.CreateThrottle(cctx, burstLimit)
|
||||
a := throttleWithCancel{
|
||||
throttle: throttle,
|
||||
cancel: cancel,
|
||||
}
|
||||
cctxV = context.WithValue(ctx, "throttle", a)
|
||||
throttles[r.RemoteAddr] = cctxV
|
||||
}
|
||||
con := context.WithValue(ctx, "throttle", a)
|
||||
|
||||
tryResult(ctx, w, r, throttles, calledLastHour)
|
||||
tryResult(cctxV, w, r, calledLastHour)
|
||||
})
|
||||
|
||||
err := http.ListenAndServe(":3333", nil)
|
||||
|
|
@ -51,19 +55,14 @@ 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, throttles map[string]<-chan time.Time, calledLastHour []string) {
|
||||
func tryResult(ctx context.Context, w http.ResponseWriter, r *http.Request, 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
|
||||
}
|
||||
throttle := ctx.Value("throttle").(throttleWithCancel).throttle
|
||||
payload := throttling.Payload{
|
||||
R: r,
|
||||
W: w,
|
||||
|
|
|
|||
|
|
@ -24,9 +24,6 @@ type Payload struct {
|
|||
// CallFunction allows burst rate limiting client calls with the
|
||||
// payloads.
|
||||
func CallFunction(ctx context.Context, client Client, payload *Payload, throttle <-chan time.Time) {
|
||||
//ctx, cancel := context.WithCancel(ctx)
|
||||
// defer cancel()
|
||||
|
||||
<-throttle // rate limit our client calls
|
||||
client.Call(payload)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue