如何在Golang中创建和渲染基本模板? - 创建登录表单 - 将其保存在UserLogin struct(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)
}
答案 0 :(得分:2)
在谷歌appengine控制台中将auth更改为openid提供程序
然后添加以下代码,它会检查一个appengine用户是否已登录,如果不是,他将向他显示google登录页面。
u := user.Current(c)
if u == nil {
url, err := user.LoginURL(c, r.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
return
}