正如我们在 15.6/7 节中所看到的,template
包经常被用于 web 应用,所以也可以被用于 GAE 应用。下面的应用程序让用户输入一个文本。首先,一个留言簿表格显示出来(通过 /
根处理程序),当它被发布时,sign()
处理程序将这个文本替换到产生的 html
响应中。sign()
函数通过调用 r.FormValue
获得窗口数据,并将其传递给 signTemplate.Execute()
,后者将渲染的模板写入 http.ResponseWriter
。
编辑文件 helloworld2.go,用下面的 Go 代码替换它,并试运行:
Listing 20.4 helloworld2_version3.go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| 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) } }
|
链接