counter: change http rate limiter criteria

This commit is contained in:
Chris Sexton 2022-07-17 13:47:49 -04:00
parent 72c32e1c16
commit 96229c9e11
1 changed files with 11 additions and 5 deletions

View File

@ -4,6 +4,7 @@ import (
"embed" "embed"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/velour/catbase/bot/user"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strconv" "strconv"
@ -23,11 +24,14 @@ func (p *CounterPlugin) registerWeb() {
r := chi.NewRouter() r := chi.NewRouter()
requests := p.cfg.GetInt("counter.requestsPer", 1) requests := p.cfg.GetInt("counter.requestsPer", 1)
seconds := p.cfg.GetInt("counter.seconds", 1) seconds := p.cfg.GetInt("counter.seconds", 1)
r.Use(httprate.LimitByIP(requests, time.Duration(seconds)*time.Second)) dur := time.Duration(seconds) * time.Second
r.HandleFunc("/api/users/{user}/items/{item}/increment/{delta}", p.mkIncrementByNAPI(1)) subrouter := chi.NewRouter()
r.HandleFunc("/api/users/{user}/items/{item}/decrement/{delta}", p.mkIncrementByNAPI(-1)) subrouter.Use(httprate.LimitByIP(requests, dur))
r.HandleFunc("/api/users/{user}/items/{item}/increment", p.mkIncrementAPI(1)) subrouter.HandleFunc("/api/users/{user}/items/{item}/increment/{delta}", p.mkIncrementByNAPI(1))
r.HandleFunc("/api/users/{user}/items/{item}/decrement", p.mkIncrementAPI(-1)) subrouter.HandleFunc("/api/users/{user}/items/{item}/decrement/{delta}", p.mkIncrementByNAPI(-1))
subrouter.HandleFunc("/api/users/{user}/items/{item}/increment", p.mkIncrementAPI(1))
subrouter.HandleFunc("/api/users/{user}/items/{item}/decrement", p.mkIncrementAPI(-1))
r.Mount("/", subrouter)
r.HandleFunc("/api", p.handleCounterAPI) r.HandleFunc("/api", p.handleCounterAPI)
r.HandleFunc("/", p.handleCounter) r.HandleFunc("/", p.handleCounter)
p.b.RegisterWebName(r, "/counter", "Counter") p.b.RegisterWebName(r, "/counter", "Counter")
@ -250,12 +254,14 @@ func (p *CounterPlugin) handleCounterAPI(w http.ResponseWriter, r *http.Request)
if err != nil { if err != nil {
w.WriteHeader(500) w.WriteHeader(500)
fmt.Fprint(w, err) fmt.Fprint(w, err)
log.Error().Err(err).Msg("Error getting items")
return return
} }
data, err := json.Marshal(all) data, err := json.Marshal(all)
if err != nil { if err != nil {
w.WriteHeader(500) w.WriteHeader(500)
fmt.Fprint(w, err) fmt.Fprint(w, err)
log.Error().Err(err).Msg("Error marshaling items")
return return
} }
fmt.Fprint(w, string(data)) fmt.Fprint(w, string(data))