This commit is contained in:
lbenedar
2026-03-05 17:46:26 +03:00
parent c2883b9916
commit b50cd42f4f
8 changed files with 70 additions and 30 deletions

View File

@@ -13,10 +13,10 @@ import (
)
type snippetCreateForm struct {
Title string
Content string
Expires int
validator.Validator
Title string `form:"title"`
Content string `form:"content"`
Expires int `form:"expires"`
validator.Validator `form:"-"`
}
func (app *application) render(w http.ResponseWriter, status int, page string, data *templateData) {
@@ -88,24 +88,13 @@ func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
}
func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
var form snippetCreateForm
err := app.decodePostForm(r, &form)
if err != nil {
app.clientError(w, http.StatusBadRequest)
return
}
expires, err := strconv.Atoi(r.PostForm.Get("expires"))
if err != nil {
app.clientError(w, http.StatusBadRequest)
return
}
form := snippetCreateForm{
Title: r.PostForm.Get("title"),
Content: r.PostForm.Get("content"),
Expires: expires,
}
form.CheckField(validator.NotBlank(form.Title), "title", "This field cannot be blank")
form.CheckField(validator.MaxChars(form.Title, 100), "title", "This field cannot be more than 100 character long")
form.CheckField(validator.NotBlank(form.Content), "content", "This field cannot be blank")
@@ -124,5 +113,7 @@ func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request
return
}
app.sessionManager.Put(r.Context(), "flash", "Snippet successfully created!")
http.Redirect(w, r, fmt.Sprintf("/snippet/view/%d", id), http.StatusSeeOther)
}

View File

@@ -1,9 +1,12 @@
package main
import (
"errors"
"fmt"
"net/http"
"runtime/debug"
"github.com/go-playground/form/v4"
)
func (app *application) serverError(w http.ResponseWriter, err error) {
@@ -20,3 +23,20 @@ func (app *application) clientError(w http.ResponseWriter, status int) {
func (app *application) notFound(w http.ResponseWriter) {
app.clientError(w, http.StatusNotFound)
}
func (app *application) decodePostForm(r *http.Request, snippetForm *snippetCreateForm) error {
err := r.ParseForm()
if err != nil {
return err
}
err = app.formDecoder.Decode(&snippetForm, r.PostForm)
if err != nil {
var invalidDecoderError *form.InvalidDecoderError
if errors.As(err, &invalidDecoderError) {
panic("Invalid decoder error")
}
return err
}
return nil
}

View File

@@ -7,17 +7,23 @@ import (
"log"
"net/http"
"os"
"time"
"gitea.local.lab/Lbenedar/snippetbox/internal/models"
"github.com/alexedwards/scs/mysqlstore"
"github.com/alexedwards/scs/v2"
"github.com/go-playground/form/v4"
_ "github.com/go-sql-driver/mysql"
)
type application struct {
errorLog *log.Logger
infoLog *log.Logger
snippets *models.SnippetModel
templateCache map[string]*template.Template
errorLog *log.Logger
infoLog *log.Logger
snippets *models.SnippetModel
templateCache map[string]*template.Template
formDecoder *form.Decoder
sessionManager *scs.SessionManager
}
type config struct {
@@ -47,11 +53,18 @@ func main() {
errorLog.Fatal(err)
}
formDecoder := form.NewDecoder()
sessionManager := scs.New()
sessionManager.Store = mysqlstore.New(db)
sessionManager.Lifetime = 12 * time.Hour
app := &application{
errorLog: errorLog,
infoLog: infoLog,
snippets: &models.SnippetModel{DB: db},
templateCache: templateCache,
errorLog: errorLog,
infoLog: infoLog,
snippets: &models.SnippetModel{DB: db},
templateCache: templateCache,
formDecoder: formDecoder,
sessionManager: sessionManager,
}
srv := &http.Server{

View File

@@ -17,12 +17,13 @@ func (app *application) routes() http.Handler {
fileServer := http.FileServer(http.Dir("./ui/static/"))
router.Handler(http.MethodGet, "/static/", http.StripPrefix("/static", fileServer))
router.HandlerFunc(http.MethodGet, "/", app.home)
router.HandlerFunc(http.MethodGet, "/snippet/view/:id", app.snippetView)
router.HandlerFunc(http.MethodGet, "/snippet/create", app.snippetCreate)
router.HandlerFunc(http.MethodPost, "/snippet/create", app.snippetCreatePost)
dynamic := alice.New(app.sessionManager.LoadAndSave)
router.Handler(http.MethodGet, "/", dynamic.ThenFunc(app.home))
router.Handler(http.MethodGet, "/snippet/view/:id", dynamic.ThenFunc(app.snippetView))
router.Handler(http.MethodGet, "/snippet/create", dynamic.ThenFunc(app.snippetCreate))
router.Handler(http.MethodPost, "/snippet/create", dynamic.ThenFunc(app.snippetCreatePost))
standard := alice.New(app.recoverPanic, app.logRequest, secureHeaders)
return standard.Then(router)
}

View File

@@ -14,6 +14,7 @@ type templateData struct {
Snippet *models.Snippet
Snippets []*models.Snippet
Form any
Flash string
}
func humanDate(t time.Time) string {
@@ -27,6 +28,7 @@ var functions = template.FuncMap{
func (app *application) newTemplateData(r *http.Request) *templateData {
return &templateData{
CurrentYear: time.Now().Year(),
Flash: app.sessionManager.PopString(r.Context(), "flash"),
}
}