Processing forms
We’re going to add an HTML form for creating new snippets. The form will look a bit like this:
The high-level flow for processing this form will follow a standard Post-Redirect-Get pattern and will work like so:
1. The user is shown the blank form when they make a GET request to /snippet/create .
2. The user completes the form and it’s submitted to the server via a POST request to /snippet/create .
3. The form data will be validated by our snippetCreatePost handler. If there are any validation failures the form will be re-displayed with the appropriate form fields highlighted. If it passes our validation checks, the data for the new snippet will be added to the database and then we’ll redirect the user to GET /snippet/view/{id} .
Setting up an HTML form
Let’s begin by making a new ui/html/pages/create.html file to hold the HTML for the form.
{{define "title"}}Create a new Snippet{{end}} {{define "main"}} <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> </main> {{end}}
Now let’s add a new ‘Create snippet’ link to the navigation bar for our application, so that clicking it will take the user to this new form.
{{define "nav"}} <nav> <a href="/">Home</a> <a href="/snippet/create">Create snippet</a> </nav> {{end}}
And finally, we need to update the snippetCreate handler so that it renders our new page like so:
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) { data := app.newTemplateData(r) app.render(w, r, http.StatusOK, "create.html", data) }
标签:Web,form,create,will,Application,snippet,our,Go,new From: https://www.cnblogs.com/zhangzhihui/p/18397457