this.Ctx.SetCookie("name", name, maxage, "/")
this.Ctx.SetCookie("pwd", Md5([]byte(pwd)), maxage, "/")
this.Ctx.GetCookie
cookie例子:
package controllers
import (
"github.com/astaxie/beego"
"log"
)
type TestLoginController struct {
beego.Controller
}
func (c *TestLoginController) Login() {
//获取cookie
name := c.Ctx.GetCookie("name")
password := c.Ctx.GetCookie("password")
//只是简单演示,并不严谨
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>
`)
}
}
type the_user struct {
Username string
Password string
}
func (c *TestLoginController) Post() {
u := the_user{}
if err := 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)
//删除指定的session
c.DelSession("loginuser")
//销毁全部的session
c.DestroySession()
islogin=true
fmt.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等操作,要用上面的方法
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。