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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM