Rate limiter gorilla mux

https://raw.githubusercontent.com/go-chi/httprate/master/_example/main.go

		r.Use(httprate.Limit(
			10,
			10*time.Second,
			httprate.WithKeyFuncs(httprate.KeyByIP, func(r *http.Request) (string, error) {
				token := r.Context().Value("userID").(string)
				return token, nil
			}),
			httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
				// We can send custom responses for the rate limited requests, e.g. a JSON message
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusTooManyRequests)
				w.Write([]byte(`{"error": "Too many requests"}`))
			}),
		))

You have to modify httprate.WithKeyFuncs to use your way of finding the userID (from header, from cookie, from query or whatever else).

1 Like