From 1530e3fbc2045de84513d2d2f6c3f8b2fc07385e Mon Sep 17 00:00:00 2001 From: xiemengjun Date: Tue, 1 Jan 2013 23:11:15 +0800 Subject: [PATCH] add session support --- beego.go | 39 +++++++++++++++++++++++++++++++++++++++ controller.go | 6 ++++++ 2 files changed, 45 insertions(+) diff --git a/beego.go b/beego.go index bbe6f570..0208d26d 100644 --- a/beego.go +++ b/beego.go @@ -2,9 +2,12 @@ package beego import ( "fmt" + "github.com/astaxie/session" + _ "github.com/astaxie/session/providers/memory" "net/http" "os" "path" + "strconv" ) var ( @@ -20,6 +23,13 @@ var ( ViewsPath string RunMode string //"dev" or "prod" AppConfig *Config + //related to session + SessionOn bool // wheather auto start session,default is false + SessionProvider string // default session provider memory + SessionName string // sessionName cookie's name + SessionGCMaxLifetime int64 // session's gc maxlifetime + + GlobalSessions *session.Manager //GlobalSessions ) func init() { @@ -38,6 +48,10 @@ func init() { RecoverPanic = true PprofOn = false ViewsPath = "views" + SessionOn = false + SessionProvider = "memory" + SessionName = "beegosessionID" + SessionGCMaxLifetime = 3600 } else { HttpAddr = AppConfig.String("httpaddr") if v, err := AppConfig.Int("httpport"); err != nil { @@ -71,6 +85,27 @@ func init() { } else { ViewsPath = views } + if ar, err := AppConfig.Bool("sessionon"); err != nil { + SessionOn = false + } else { + SessionOn = ar + } + if ar := AppConfig.String("sessionprovider"); ar == "" { + SessionProvider = "memory" + } else { + SessionProvider = ar + } + if ar := AppConfig.String("sessionname"); ar == "" { + SessionName = "beegosessionID" + } else { + SessionName = ar + } + if ar, err := AppConfig.Int("sessiongcmaxlifetime"); err != nil { + int64val, _ := strconv.ParseInt(strconv.Itoa(ar), 10, 64) + SessionGCMaxLifetime = int64val + } else { + SessionGCMaxLifetime = 3600 + } } StaticDir["/static"] = "static" @@ -158,5 +193,9 @@ func Run() { BeeApp.RegisterController(`/debug/pprof`, &ProfController{}) BeeApp.RegisterController(`/debug/pprof/:pp([\w]+)`, &ProfController{}) } + if SessionOn { + GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime) + go GlobalSessions.GC() + } BeeApp.Run() } diff --git a/controller.go b/controller.go index 1eae51eb..3f797bcd 100644 --- a/controller.go +++ b/controller.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "encoding/xml" + "github.com/astaxie/session" "html/template" "io/ioutil" "net/http" @@ -151,3 +152,8 @@ func (c *Controller) Input() url.Values { c.Ctx.Request.ParseForm() return c.Ctx.Request.Form } + +func (c *Controller) StartSession() (sess session.Session) { + sess = GlobalSessions.SessionStart(c.Ctx.ResponseWriter, c.Ctx.Request) + return +}