beego框架之cookie与session

发布时间:2020-07-20 21:58:14 作者:梁十八
来源:网络 阅读:782

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、mysqlredis、couchbase、memcache、postgres,用户也可以根据相应的 interface 实现自己的引擎。

beego 中使用 session 相当方便,只要在 main 入口函数中设置如下:

beego框架之cookie与session

或者通过配置文件配置如下:

beego框架之cookie与session

session 有几个方便的方法:

beego框架之cookie与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等操作,要用上面的方法

        



推荐阅读:
  1. Django 框架5-cookie和session
  2. cookie与session详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

beego 框架 cookie

上一篇:好程序员web前端分享HTML5与HTML之间有什么区别?

下一篇:Android控件之TextView

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》