menu arrow_back 湛蓝安全空间 |狂野湛蓝,暴躁每天 chevron_right All_wiki chevron_right the-way-to-go_ZH_CN chevron_right eBook chevron_right 20.6.md
  • home 首页
  • brightness_4 暗黑模式
  • cloud
    xLIYhHS7e34ez7Ma
    cloud
    湛蓝安全
    code
    Github
    20.6.md
    1.86 KB / 2024-07-16 23:14:29
        # 20.6 处理窗口
    
    正如我们在 [15.6](15.6.md)/[7](15.7.md) 节中所看到的,`template` 包经常被用于 web 应用,所以也可以被用于 GAE 应用。下面的应用程序让用户输入一个文本。首先,一个留言簿表格显示出来(通过 `/` 根处理程序),当它被发布时,`sign()` 处理程序将这个文本替换到产生的 html 响应中。`sign()` 函数通过调用 `r.FormValue` 获得窗口数据,并将其传递给 `signTemplate.Execute()`,后者将渲染的模板写入 `http.ResponseWriter`。
    
    编辑文件 helloworld2.go,用下面的 Go 代码替换它,并试运行:
    
    <u>[Listing 20.4 helloworld2_version3.go:](examples\chapter_20\helloapp\hello\helloworld2_version3.go)</u>
    
    ```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)
    	}
    }
    ```
    
    ## 链接
    
    - [目录](directory.md)
    - 上一节:[使用用户服务和探索其 API](20.5.md)
    - 下一节:[使用数据存储](20.7.md)
    
    
    
    links
    file_download