跳到主要内容

20.6 处理窗口

正如我们在 15.6/7 节中所看到的,template 包经常被用于 web 应用,所以也可以被用于 GAE 应用。下面的应用程序让用户输入一个文本。首先,一个留言簿表格显示出来(通过 / 根处理程序),当它被发布时,sign() 处理程序将这个文本替换到产生的 html 响应中。sign() 函数通过调用 r.FormValue 获得窗口数据,并将其传递给 signTemplate.Execute(),后者将渲染的模板写入 http.ResponseWriter

编辑文件 helloworld2.go,用下面的 Go 代码替换它,并试运行:

[Listing 20.4 helloworld2_version3.go:](exampleschapter_20helloapphellohelloworld2_version3.go)
package hello

import (
"fmt"
"net/http"
"template"
)

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>
`
const signTemplateHTML = `
<html>
<body>
<p>You wrote:</p>
<pre>{{html .}}</pre>
</body>
</html>
`

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

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

func root(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, guestbookForm)
}

func sign(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
err := signTemplate.Execute(w, r.FormValue("content"))
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
}
}