How to Create and Render Basic Template in Golang? - Create Login Form - Save that in UserLogin struct (datastore.put and also datastore.get)
type UserLogin struct{
UserName string
PassWord string
}
I was Created following example from some document from google: But this was created with the default user available in Go-app. Want to create Open Id login form with Go. How to do this?
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)
}
in you google appengine console change in basic settings the auth, to openid provider
then add the following code, it checks if an appengine user is logged in, if not he will show him the google login page.
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
}