-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.go
More file actions
65 lines (56 loc) · 1.4 KB
/
validate.go
File metadata and controls
65 lines (56 loc) · 1.4 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"strings"
"github.com/google/uuid"
)
func middlewareValidate(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const maxChirpLen = 140
type chirpRequest struct {
Body string `json:"body"`
UserId uuid.UUID `json:"user_id"`
}
defer r.Body.Close()
dat, err := io.ReadAll(r.Body)
if err != nil {
respondWithError(w, 500, "Something went wrong", err)
return
}
chp := chirpRequest{}
err = json.Unmarshal(dat, &chp)
if err != nil {
respondWithError(w, 400, "Something went wrong", err)
return
}
if len(chp.Body) > maxChirpLen {
respondWithError(w, 400, "Chrip is too long", err)
return
}
cleaned := cleanBodyFromProf(chp.Body)
chp.Body = cleaned
newBody, err := json.Marshal(chp)
if err != nil {
log.Printf("Failed marshaling new body %v", err)
respondWithError(w, 400, "Failed marshaling new body", err)
return
}
r.Body = io.NopCloser(bytes.NewBuffer(newBody))
next.ServeHTTP(w, r)
})
}
func cleanBodyFromProf(s string) string {
illegalWords := map[string]struct{}{"kerfuffle": {}, "sharbert": {}, "fornax": {}}
words := strings.Split(s, " ")
for i, word := range words {
if _, ok := illegalWords[strings.ToLower(word)]; ok {
words[i] = "****"
}
}
cleaned := strings.Join(words, " ")
return cleaned
}