lets-go:8.2 create form

This commit is contained in:
tamsin johnson 2024-01-25 22:31:27 -08:00
parent d1b9b2b269
commit 1931b047fc
4 changed files with 49 additions and 4 deletions

View File

@ -52,14 +52,27 @@ func (app *application) snippetView(w http.ResponseWriter, r *http.Request) {
// (app *application) snippetCreate ...
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Form for new snippet, plz?"))
data := app.newTemplateData(r)
app.render(w, r, http.StatusOK, "create.tmpl", data)
}
// snippetCreatePost ...
func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request) {
title := "0 snail"
content := "0 snail\nClimb Mount Fuji,\nBut slowly, slowly!\n\n - Kobayashi Issa"
expires := 7
err := r.ParseForm()
if err != nil {
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 {
app.clientError(w, http.StatusBadRequest)
return
}
id, err := app.snippets.Insert(title, content, expires)
if err != nil {

View File

@ -11,6 +11,14 @@ import (
func (app *application) routes() http.Handler {
router := httprouter.New()
router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.notFound(w)
})
router.MethodNotAllowed = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.clientError(w, http.StatusMethodNotAllowed)
})
// setup server for static files
fileServer := http.FileServer(http.Dir("./ui/static"))
router.Handler(http.MethodGet, "/static/*filepath", http.StripPrefix("/static", fileServer))

View File

@ -0,0 +1,23 @@
{{define "title"}}Create a New Snippet{{end}}
{{define "main"}}
<form action='/snippet/create' method='POST'>
<div>
<label>Title:</label>
<input type='text' name='title'>
</div>
<div>
<label>Content:</label>
<textarea name='content'></textarea>
</div>
<div>
<label>Delete in:</label>
<input type='radio' name='expires' value='365' checked> One Year
<input type='radio' name='expires' value='7'> One Week
<input type='radio' name='expires' value='1'> One Day
</div>
<div>
<input type='submit' value='Publish Snippet'>
</div>
</form>
{{end}}

View File

@ -1,5 +1,6 @@
{{define "nav"}}
<nav>
<a href="/">Home</a>
<a href="/snippet/create">Create Snippet</a>
</nav>
{{end}}