如何在 Golang 中创建和渲染基本模板?- 创建登录表单 - 将其保存在 UserLogin 结构中(datastore.put 和 datastore.get)
type UserLogin struct{
UserName string
PassWord string
}
我是从谷歌的一些文档中创建的以下示例:但这是使用 Go-app 中可用的默认用户创建的。想用 Go 创建 Open Id 登录表单。这个怎么做?
package hello
import (
"appengine"
"appengine/datastore"
"html/template"
"net/http"
)
//AdminData Structure
type AdminData struct {
UserName string
UserPassword string
}
func init() {
http.HandleFunc("/", root)
http.HandleFunc("/login", login)
}
func root(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
q := datastore.NewQuery("AdminData").Limit(10)
adminsdata := make([]AdminData, 0, 10)
if _, err := q.GetAll(c, &adminsdata); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := loginTemplate.Execute(w, adminsdata); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
var loginTemplate = template.Must(template.New("book").Parse(loginTemplateHTML))
const loginTemplateHTML = `
<html>
<body>
{{range .}}
{{with .UserName}}
<p><b>{{.}}</b> user name:</p>
{{else}}
<p>An anonymous person wrote:</p>
{{end}}
<pre>{{.UserPassword}}</b> password:</p></pre>
{{end}}
<form action="/login" method="post">
<div>User Name : <input type="text" name="userName" value=""> </div>
<div>Password : <input type="password" name="userPassword" value=""> </div>
<div><input type="submit" value="Login"></div>
</form>
</body>
</html>
`
func login(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
g := AdminData{
UserName : r.FormValue("userName"),enter code here
UserPassword : r.FormValue("userPassword"),
}
_, err := datastore.Put(c, datastore.NewIncompleteKey(c, "AdminData", nil), &g)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}