This commit is contained in:
lbenedar
2026-03-05 15:33:47 +03:00
parent 3015b7318e
commit 3bd8a8e1c7
3 changed files with 46 additions and 19 deletions

View File

@@ -13,6 +13,13 @@ import (
"github.com/julienschmidt/httprouter"
)
type snippetCreateForm struct {
Title string
Content string
Expires int
FieldErrors map[string]string
}
func (app *application) render(w http.ResponseWriter, status int, page string, data *templateData) {
ts, ok := app.templateCache[page]
if !ok {
@@ -74,6 +81,10 @@ func (app *application) snippetView(w http.ResponseWriter, r *http.Request) {
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
data := app.newTemplateData(r)
data.Form = snippetCreateForm{
Expires: 365,
}
app.render(w, http.StatusOK, "create.tmpl", data)
}
@@ -83,8 +94,6 @@ func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request
app.clientError(w, http.StatusBadRequest)
return
}
title := r.PostForm.Get("title")
content := r.PostForm.Get("content")
expires, err := strconv.Atoi(r.PostForm.Get("expires"))
if err != nil {
@@ -92,27 +101,35 @@ 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 be more than 100 character long"
form := snippetCreateForm{
Title: r.PostForm.Get("title"),
Content: r.PostForm.Get("content"),
Expires: expires,
FieldErrors: map[string]string{},
}
if strings.TrimSpace(content) == "" {
fieldErrors["content"] = "This field cannot be blank"
if strings.TrimSpace(form.Title) == "" {
form.FieldErrors["title"] = "This field cannot be blank"
} else if utf8.RuneCountInString(form.Title) > 100 {
form.FieldErrors["title"] = "This field cannot be more than 100 character long"
}
if expires != 1 && expires != 7 && expires != 365 {
fieldErrors["expires"] = "This field must equal 1, 7 and 365"
if strings.TrimSpace(form.Content) == "" {
form.FieldErrors["content"] = "This field cannot be blank"
}
if len(fieldErrors) > 0 {
fmt.Fprint(w, fieldErrors)
if form.Expires != 1 && form.Expires != 7 && form.Expires != 365 {
form.FieldErrors["expires"] = "This field must equal 1, 7 and 365"
}
if len(form.FieldErrors) > 0 {
data := app.newTemplateData(r)
data.Form = form
app.render(w, http.StatusUnprocessableEntity, "create.tmpl", data)
return
}
id, err := app.snippets.Insert(title, content, expires)
id, err := app.snippets.Insert(form.Title, form.Content, form.Expires)
if err != nil {
app.serverError(w, err)
return