Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rest server rate limit #11

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
21 changes: 20 additions & 1 deletion pkg/restServer/restServer.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
"time"

"github.com/gorilla/mux"
"github.com/throttled/throttled/v2"
"github.com/throttled/throttled/v2/store/memstore"
)

const restPrefix = "/api/v1"
Expand Down Expand Up @@ -422,6 +424,23 @@ func Start(address, webDir string, g *gpioControl.Gpio, f *flashromControl.Flash
log.Fatal(err)
}

store, err := memstore.New(65536)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Silentsky0 lets add some comments to this block of code to explain why we added this limit, we can also put here link to issue

if err != nil {
log.Fatal(err)
}
quota := throttled.RateQuota{
MaxRate: throttled.PerSec(10),
MaxBurst: 5,
}
rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
if err != nil {
log.Fatal(err)
}
httpRateLimiter := throttled.HTTPRateLimiter{
RateLimiter: rateLimiter,
VaryBy: &throttled.VaryBy{Path: true},
}

router := mux.NewRouter()
router.Handle("/", fs).Methods("GET")
for _, file := range files {
Expand All @@ -441,5 +460,5 @@ func Start(address, webDir string, g *gpioControl.Gpio, f *flashromControl.Flash
router.HandleFunc(restPrefix+"/flash", logFunc(startFlashing)).Methods("PUT")
router.HandleFunc(restPrefix+"/flash", logFunc(getFlashingState)).Methods("GET")

http.ListenAndServe(address, router)
http.ListenAndServe(address, httpRateLimiter.RateLimit(router))
}