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等操作,要用上面的方法
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。