beego框架之cookie与session
this.Ctx.SetCookie("name", name, maxage, "/")
this.Ctx.SetCookie("pwd", Md5([]byte(pwd)), maxage, "/")
this.Ctx.GetCookie
cookie例子:
packagecontrollersimport("github.com/astaxie/beego""log")typeTestLoginControllerstruct{beego.Controller}func(c*TestLoginController)Login(){//获取cookiename:=c.Ctx.GetCookie("name")password:=c.Ctx.GetCookie("password")//只是简单演示,并不严谨ifname!=""{c.Ctx.WriteString("Username:"+name+"Password:"+password)}else{c.Ctx.WriteString(`<html><formaction="http://127.0.0.1:8080/test_login"method="post"><inputtype="text"name="Username"><inputtype="password"name="Password"><inputtype="submit"value="提交"></form></html>`)}}typethe_userstruct{UsernamestringPasswordstring}func(c*TestLoginController)Post(){u:=the_user{}iferr:=c.ParseForm(&u);err!=nil{log.Fatal(err)}c.Ctx.SetCookie("name",u.Username,100,"/")c.Ctx.SetCookie("password",u.Password,100,"/")c.Ctx.WriteString("Username:"+u.Username+"Password:"+u.Password)}
beego 内置了 session 模块,目前 session 模块支持的后端引擎包括 memory、cookie、file、mysql、redis、couchbase、memcache、postgres,用户也可以根据相应的 interface 实现自己的引擎。
beego 中使用 session 相当方便,只要在 main 入口函数中设置如下:
或者通过配置文件配置如下:
session 有几个方便的方法:
session例子:
c.SetSession("loginuser","adminuser")fmt.Println("当前的session:")fmt.Println(c.CruSession)//删除指定的sessionc.DelSession("loginuser")//销毁全部的sessionc.DestroySession()islogin=truefmt.Println("当前的session:")fmt.Println(c.CruSession)c.SetSession("name","zhangsan")//注意:要能c.Ctx.WriteString(name),就要让它符合输出的类型name:=fmt.Sprintf("%v",c.GetSession("name"))c.Ctx.WriteString(name)
beego.BConfig.WebConfig.Session.SessionOn = true设置后不能进行SetSession等操作,要用上面的方法
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。