-
Notifications
You must be signed in to change notification settings - Fork 0
/
validateChirp.go
69 lines (56 loc) · 1.46 KB
/
validateChirp.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"encoding/json"
"net/http"
"strings"
)
// create a request struct type
type chirpReqValidate struct {
Body string `json:"body"`
}
// create a respond struct type
type ResChirpValidate struct {
Valid bool `json:"valid"`
CleanBody string `json:"cleaned_body,omitempty"`
Error string `json:"error,omitempty"`
}
// handler controller that takes in the instance of the request and then performs the logic
func ValidateChirpHandler(w http.ResponseWriter, r *http.Request) {
//request instance
var req chirpReqValidate
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(req.Body) > 140 {
validateRes := ResChirpValidate{
Valid: false,
Error: "Chirp is too long",
}
json.NewEncoder(w).Encode(validateRes)
return
}
validateRes := ResChirpValidate{
Valid: true,
CleanBody: Profane(req.Body),
}
json.NewEncoder(w).Encode(validateRes)
}
func Profane(Chirp string) string {
profaneWords := []string{"shit", "punk", "ass", "drugs", "guns", "bITCHES"}
cleanWords := make([]string, 0)
words := strings.Split(Chirp, " ")
for _, word := range words {
lowercaseWord := strings.ToLower(strings.Trim(word, "!.,?"))
for _, pfWrd := range profaneWords {
lowerPfWrd := strings.ToLower(pfWrd)
if lowercaseWord == lowerPfWrd {
word = "****"
break
}
}
cleanWords = append(cleanWords, word)
}
return strings.Join(cleanWords, " ")
}