English

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 (
    "fmt"
    "http"
    "template"
)

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

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

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

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

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

const signTemplateHTML = `
<html>
  <body>
    <p>You wrote:</p>
    <pre>{{html .}}</pre>
  </body>
</html>
`

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 filtered with the html filter to escape HTML special characters.

Next...

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.