示例:
1)通过模板方法渲染一个登录页面。例如:这是 index.html
{{ define "title" }}Guestbook{{ end }}
{{ define "content" }}
<form action="/login" method="post">
<div><label>UserName : </label><input name="username" type="text" /></div>
<div><label>Password : </label><input name="password" type="password" /></div>
<div><input type="submit" value="login"></div>
</form>
{{ end }}
2) hello.go 文件:
package main
import (
"fmt"
"html/template"
"net/http"
)
var index = template.Must(template.ParseFiles(
"templates/base.html",
"templates/index.html",
))
//UserLogin struct is created
type UserLogin struct{
UserName string
PassWord string
}
func handler(w http.ResponseWriter, r *http.Request) {
index.Execute(w, nil)
}
func login(w http.ResponseWriter, r *http.Request) {
remPartOfURL := r.URL.Path[len("/login/"):]
if r.Method == "POST" {
http.Error(w, fmt.Sprintf("First Name: %s", r.FormValue("username")), http.StatusOK)
http.Error(w, fmt.Sprintf("Password: %s", r.FormValue("password")), http.StatusOK)
}
}
func init() {
http.HandleFunc("/", handler)
http.HandleFunc("/login/", login)
}
在 login() 的这个示例中:能够打印 r.FormValue("username") 和 r.FormValue("password") 但如何“放入”数据存储区以及如何从数据存储区“获取”。