Google App Engine

Handling Forms

If we want users to be able to post their own greetings, we need a way to process information submitted by the user with a web form. The Go http package makes processing form data easy.

Handling Web Forms

Replace the contents of myapp/hello/hello.go with the following:

package hello

import (

func init() {
    http.HandleFunc("/", root)
    http.HandleFunc("/sign", sign)

func root(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, guestbookForm)

const guestbookForm = `
    <form action="/sign" method="post">
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>

func sign(w http.ResponseWriter, r *http.Request) {
    err := signTemplate.Execute(w, r.FormValue("content"))
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)

var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML))

const signTemplateHTML = `
    <p>You wrote:</p>

Reload the page to see the form, then try submitting a message.

This version has two handlers: the path / is mapped to root, which displays a web form. The path /sign is mapped to sign, which displays the data submitted by the web form.

The sign function gets the form data by calling r.FormValue and passes it to signTemplate.Execute that writes the rendered template to the http.ResponseWriter. In the template code, the content is automatically filtered to escape HTML special characters. The automatic escaping is a property of the html/template package, as distinct from text/template.


Now that we can collect information from the user, we need a place to put it and a way to get it back.

Continue to Using the Datastore.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.