一、cookie的用法html
this.Ctx.SetCookie("name", name, maxage, "/") this.Ctx.SetCookie("pwd", Md5([]byte(pwd)), maxage, "/") this.Ctx.GetCookie
二、session控制mysql
beego 內置了 session 模塊,目前 session 模塊支持的後端引擎包括 memory、cookie、file、mysql、redis、couchbase、memcache、postgres,用戶也能夠根據相應的 interface 實現本身的引擎。git
beego 中使用 session 至關方便,只要在 main 入口函數中設置以下:github
beego.BConfig.WebConfig.Session.SessionOn = true
或者經過配置文件配置以下:web
sessionon = true
session 有幾個方便的方法:redis
session 操做主要有設置 session、獲取 session、刪除 session。sql
三、cookie與session用法後端
示例:cookie
routers/router.gosession
package routers import ( "web/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/test_input", &controllers.TestInputController{}, "get:Get;post:Post") beego.Router("/test_login", &controllers.TestLoginController{}, "get:Login;post:Post") }
verws/main.go
package main import ( _ "web/routers" "github.com/astaxie/beego" ) func main() { beego.BConfig.WebConfig.Session.SessionOn = true beego.Run() }
controllers/testInput.go
package controllers import ( "github.com/astaxie/beego" ) type TestInputController struct { beego.Controller } type User struct{ Username string Password string } func (c *TestInputController) Get(){ //id := c.GetString("id") //c.Ctx.WriteString("<html>" + id + "<br/>") //name := c.Input().Get("name") //c.Ctx.WriteString(name + "</html>") name := c.GetSession("name") password := c.GetSession("password") if nameString, ok := name.(string); ok && nameString != ""{ c.Ctx.WriteString("Name:" + name.(string) + " password:" + password.(string)) }else{ c.Ctx.WriteString(`<html><form action="http://127.0.0.1:8080/test_input" method="post"> <input type="text" name="Username"/> <input type="password" name="Password"/> <input type="submit" value="提交"/> </form></html>`) } } func (c *TestInputController) Post(){ u := User{} if err:=c.ParseForm(&u) ; err != nil{ //process error } c.Ctx.WriteString("Username:" + u.Username + " Password:" + u.Password) }
controllers/testLogin.go
package controllers import ( "github.com/astaxie/beego" ) type TestLoginController struct { beego.Controller } type UserInfoV2 struct{ Username string Password string } func (c *TestLoginController) Login(){ name := c.Ctx.GetCookie("name") password := c.Ctx.GetCookie("password") //do verify work if name != ""{ c.Ctx.WriteString("Username:" + name + " Password:" + password) }else{ c.Ctx.WriteString(`<html><form action="http://127.0.0.1:8080/test_login" method="post"> <input type="text" name="Username"/> <input type="password" name="Password"/> <input type="submit" value="提交"/> </form></html>`) } } func (c *TestLoginController) Post(){ u := UserInfoV2{} if err:=c.ParseForm(&u) ; err != nil{ //process error } c.Ctx.SetCookie("name", u.Username, 100, "/") c.Ctx.SetCookie("password", u.Password, 100, "/") c.SetSession("name", u.Username) c.SetSession("password", u.Password) c.Ctx.WriteString("Username:" + u.Username + " Password:" + u.Password) }