-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
blackwords.go
39 lines (33 loc) · 987 Bytes
/
blackwords.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
package rest
import (
"bytes"
"io"
"net/http"
"strings"
)
// BlackWords middleware doesn't allow some words in the request body
func BlackWords(words ...string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if content, err := io.ReadAll(r.Body); err == nil {
body := strings.ToLower(string(content))
r.Body = io.NopCloser(bytes.NewReader(content))
if body != "" {
for _, word := range words {
if strings.Contains(body, strings.ToLower(word)) {
w.WriteHeader(http.StatusForbidden)
RenderJSON(w, JSON{"error": "one of blacklisted words detected"})
return
}
}
}
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
// BlackWordsFn middleware uses func to get the list and doesn't allow some words in the request body
func BlackWordsFn(fn func() []string) func(http.Handler) http.Handler {
return BlackWords(fn()...)
}