Skip to content

Instantly share code, notes, and snippets.

@hotafrika
Created November 9, 2022 13:03
Show Gist options
  • Save hotafrika/c046cceda8f6cfe9da2f23fb7d473e8a to your computer and use it in GitHub Desktop.
Save hotafrika/c046cceda8f6cfe9da2f23fb7d473e8a to your computer and use it in GitHub Desktop.
medium / chi rate limiter
func main() {
router := chi.NewRouter()
router.Use(httprate.LimitByIP(100, time.Minute))
router.Get("/info", infoHandler)
router.Group(func(router chi.Router) {
router.Use(httprate.Limit(20, time.Minute, httprate.WithKeyFuncs(
httprate.KeyByIP,
httprate.KeyByEndpoint,
)))
router.Use(authMiddleware)
router.Get("/profile", profileHandler)
router.Route("/stat", func(router chi.Router) {
router.Use(httprate.Limit(5, time.Minute,
httprate.WithKeyFuncs(
func(r *http.Request) (string, error) {
token := r.Context().Value("userID").(string)
return token, nil
},
),
))
router.Get("/", statHandler)
})
})
_ = http.ListenAndServe(":8080", router)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment