From 5316e01ccec03a888b70a719050b6a2ca67bc1f1 Mon Sep 17 00:00:00 2001 From: tamsin johnson Date: Thu, 25 Jan 2024 22:57:49 -0800 Subject: [PATCH] lets-go:8.3 some validation --- snippetbox/cmd/web/handlers.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/snippetbox/cmd/web/handlers.go b/snippetbox/cmd/web/handlers.go index 6ce05bb..be329fd 100644 --- a/snippetbox/cmd/web/handlers.go +++ b/snippetbox/cmd/web/handlers.go @@ -5,6 +5,8 @@ import ( "fmt" "net/http" "strconv" + "strings" + "unicode/utf8" "github.com/julienschmidt/httprouter" "snippetbox.chaosfem.tw/internal/models" @@ -74,6 +76,27 @@ func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request return } + fieldErrors := make(map[string]string) + + if strings.TrimSpace(title) == "" { + fieldErrors["title"] = "This field cannot be blank" + } else if utf8.RuneCountInString(title) > 100 { + fieldErrors["title"] = "This field cannot contain more than 100 characters" + } + + if strings.TrimSpace(content) == "" { + fieldErrors["content"] = "This field cannot be blank" + } + + if expires != 1 && expires != 7 && expires != 365 { + fieldErrors["expires"] = "This field must equal 1, 7 or 365" + } + + if len(fieldErrors) > 0 { + fmt.Fprint(w, fieldErrors) + return + } + id, err := app.snippets.Insert(title, content, expires) if err != nil { app.serverError(w, r, err)