0

如何在 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)
}
4

1 回答 1

2

在您的 google appengine 控制台中,将身份验证的基本设置更改为 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
}
于 2013-06-18T06:41:09.810 回答