-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
43 lines (39 loc) · 1019 Bytes
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import (
"context"
"strconv"
"go.uber.org/zap"
)
// excessiveDiceMiddleware checks the expression available in the request
// context to determine if the desired roll is dangerous/will require too many
// dice.
func excessiveDiceMiddleware(next HandlerFunc) HandlerFunc {
return HandlerFunc(func(ctx context.Context) {
if excessiveDice(ctx) {
return
}
next(ctx)
})
}
// excessiveDice predicts whether the context's dice expression would exceed
// the maximum allowed number of dice per roll.
func excessiveDice(ctx context.Context) bool {
roll, ok := ctx.Value(KeyRollInput).(*NamedRollInput)
if !ok {
panic("dice expression missing from context")
}
matches := manyDice.FindAllStringSubmatch(roll.Expression, -1)
count := 0
for _, ext := range matches {
num, _ := strconv.Atoi(ext[1])
count += num
}
if count > DiceGolem.MaxDice {
logger.Debug("too many dice",
zap.String("expression", roll.Expression),
zap.Int("count", count),
)
return true
}
return false
}