github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/web/examples/web.go (about) 1 // Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build ingore 6 7 package main 8 9 import ( 10 "log" 11 "os" 12 "strings" 13 "text/template" 14 15 "github.com/chai2010/gopkg/web" 16 ) 17 18 const page = ` 19 <html> 20 <meta charset="utf-8"/> 21 <body> 22 {{if .Value}}. 23 Hi {{.Value}}. 24 <form method="post" action="/logout"> 25 <input type="submit" name="method" value="logout" /> 26 </form> 27 You will logout after 10 seconds. Then try to reload. 28 {{else}} 29 <form method="post" action="/login"> 30 <label for="name">Name:</label> 31 <input type="text" id="name" name="name" value="" /> 32 <input type="submit" name="method" value="login" /> 33 </form> 34 {{end}} 35 </body> 36 </html> 37 ` 38 39 var tmpl = template.Must(template.New("x").Parse(page)) 40 41 func getSession(ctx *web.Context, manager *web.SessionManager) *web.Session { 42 id, _ := ctx.GetSecureCookie("SessionId") 43 session := manager.GetSessionById(id) 44 ctx.SetSecureCookie("SessionId", session.Id, int64(manager.GetTimeout())) 45 ctx.SetHeader("Pragma", "no-cache", true) 46 return session 47 } 48 49 func main() { 50 logger := log.New(os.Stdout, "", log.Ldate|log.Ltime) 51 manager := web.NewSessionManager(logger) 52 manager.OnStart(func(session *web.Session) { 53 println("started new session") 54 }) 55 manager.OnEnd(func(session *web.Session) { 56 println("abandon") 57 }) 58 manager.SetTimeout(10) 59 60 web.Config.CookieSecret = "7C19QRmwf3mHZ9CPAaPQ0hsWeufKd" 61 web.Get("/", func(ctx *web.Context) { 62 session := getSession(ctx, manager) 63 tmpl.Execute(ctx, session) 64 }) 65 web.Post("/login", func(ctx *web.Context) { 66 name := strings.Trim(ctx.Params["name"], " ") 67 if name != "" { 68 logger.Printf("User \"%s\" login", name) 69 70 // XXX: set user own object. 71 getSession(ctx, manager).Value = name 72 } 73 ctx.Redirect(302, "/") 74 }) 75 web.Post("/logout", func(ctx *web.Context) { 76 session := getSession(ctx, manager) 77 if session.Value != nil { 78 // XXX: get user own object. 79 logger.Printf("User \"%s\" logout", session.Value.(string)) 80 session.Abandon() 81 } 82 ctx.Redirect(302, "/") 83 }) 84 web.Run(":6061") 85 }