4. Beego 框架之cookie与session

cookie是存储在客户端的,用于标识客户身份的!

what is session

session 是存储在服务端,也是用于客户身份标识,用于跟踪用户会话。

BeeGo session保存方式

Beego内置了session模块,目前session模块支持的后端引擎包括memory,cookie,file,mysql,redis,couchbase,memcache、postgres,用户也可以根据相应的interface实现自己的引擎。

beego 启用session

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

beego.BConfig.WebConfig.Session.SessionOn = true

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

sessionon = true

session 有几个方便的方法

1. SetSession(name string,value interface{})
2. GetSession(name string,) interface{}
3. DelSession(name string)
4. SessionRegenerateID()
5. DestorySession()

拿代码来说话

router.go的代码

package routers

import (
	"WEB/controllers"

	"github.com/astaxie/beego"
)

func init() {
	beego.Router("/test_login", &controllers.TestLoginController{}, "post:PostData;get:Login")   // 唯一添加了这条
}

controllers的文件夹

testlogin.go
// testlogin
package controllers

import (
	"github.com/astaxie/beego"
)

type TestLoginController struct {
	beego.Controller
}

func (c *TestLoginController) SelfTest() {
	c.Ctx.WriteString("this is myself  controller!")
}

func (c *TestLoginController) Login() {
	name := c.Ctx.GetCookie("name")
	password := c.Ctx.GetCookie("password")

	if name != "" {
		c.Ctx.WriteString("Username:" + name + "password:" + password)
	} else {
		formData := `<html><form action="/test_login" method="post">
		 <input type="text" name="Username">
		 <input type="password" name="Password">
		<input type="submit" value="post">
			</html>
		`
		c.Ctx.WriteString(formData)
	}
}

func (c *TestLoginController) PostData() {
	u := User{}
	if err := c.ParseForm(&u); err != nil {

	}
	c.Ctx.SetCookie("name", u.Username, 100, "/")  // 设置cookie
	c.Ctx.SetCookie("password", u.Password, 100, "/")  // 设置cookie
	c.Ctx.WriteString("username:" + u.Username + "   password:" + u.Password)
}

我们通过c.Ctx.SetCookie设置cookie后,你在浏览器输入http://ip:port/test_login,填写用户密码提交以后,再次访问test_login,那么是不需填写用户密码的了,因为已经保存了session与cookie。

posted @ 2017-12-28 18:58  温柔易淡  阅读(8325)  评论(2编辑  收藏  举报