Esempio n. 1
0
func main() {
	// For testing purposes, we want cookies to be sent over HTTP too (not just HTTPS):
	session.Global.Close()
	session.Global = session.NewCookieManagerOptions(session.NewInMemStore(), &session.CookieMngrOptions{AllowHTTP: true})

	log.Println("Session demo is about to start. Visit: localhost:8080/demo")
	http.HandleFunc("/demo", myHandler)
	http.ListenAndServe(":8080", nil)
}
Esempio n. 2
0
// myHandler handles everything: page/form rendering, processing login form submits, logout submits.
// If login is successful, a new session is created. If logout is successful, session is removed.
func myHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	// Create session manager:
	// For testing purposes, we want cookies to be sent over HTTP too (not just HTTPS):
	sessmgr := session.NewCookieManagerOptions(session.NewMemcacheStore(ctx), &session.CookieMngrOptions{AllowHTTP: true})
	defer sessmgr.Close() // Note the Close(): it will ensure changes made to the session are auto-saved in Memcache.

	m := map[string]interface{}{}

	sess := sessmgr.Get(r)
	if sess != nil {
		// Already logged in
		if r.FormValue("Logout") != "" {
			sessmgr.Remove(sess, w) // Logout user
			sess = nil
		} else {
			sess.SetAttr("Count", sess.Attr("Count").(int)+1)
		}
	} else {
		// Not logged in
		if r.FormValue("Login") != "" {
			if userName := r.FormValue("UserName"); userName != "" && r.FormValue("Password") == "a" {
				// Successful login. New session with initial constant and variable attributes:
				sess = session.NewSessionOptions(&session.SessOptions{
					CAttrs: map[string]interface{}{"UserName": userName},
					Attrs:  map[string]interface{}{"Count": 1},
				})
				sessmgr.Add(sess, w)
			} else {
				m["InvalidLogin"] = true
			}
		}
	}

	if sess != nil {
		m["UserName"] = sess.CAttr("UserName")
		m["Count"] = sess.Attr("Count")
	}

	if err := templ.Execute(w, m); err != nil {
		log.Println("Error:", err)
	}
}