我有一个routes.go文件,如下所示:
func GetRouter(services Servicesr) *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/api/)
return router
}
我想对我的/api/services进行速率限制,并且我正在尝试执行以下操作:
在limiter.go中,我有这个:
package limiter
import (
"golang.org/x/time/rate"
"net/http"
)
var limiter = rate.NewLimiter(1, 3)
func Limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if limiter.Allow() == false {
http.Error(w, http.StatusText(429), http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
但是我似乎无法掌握如何限制路由器的速率.api/services的HandlerFunc
最佳答案
将router.HandleFunc
的api/services
行更改为以下内容:
router.Handle("/api/services", Limit(http.HandlerFunc(services.GetServices))).Methods(http.MethodGet)
关于go - Go上的API速率限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59619765/