Beego之Cookie
1.Http是無狀態的協議,服務器不能記錄瀏覽器的訪問狀態,也就是服務器不能區分兩次請求是否是來自同一個客戶端。
2.Cookie實際上是服務器保存在瀏覽器上的一段信息,瀏覽器有了Cookie之后,每次向服務器發送請求都會帶着該信息進行訪問,服務器在收到請求之后,就可以通過該信息進行處理。
3.Cookie由服務器創建,並發給瀏覽器,最終由瀏覽器保存。
Cookie一般用於保持用戶登陸狀態,電商網站的購物車等。
關於Cookie的詳細介紹,我們在之前的章節中已經說的很清除了,本章我們重點說明一下Beego如何操作Cookie。
Beego操作Cookie,無非就是兩個方法,一個是設置,一個是獲取:
c.Ctx.SetCookie(key,value,有效時長...)
c.Ctx.GetCookie(key)
源代碼如下:
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { ctx.Output.Cookie(name, value, others...) } func (ctx *Context) GetCookie(key string) string { return ctx.Input.Cookie(key) }
一、設置Cookie
首先新建一個Controller:
新建go文件testlogin.go,並創建TestLoginController:
type TestLoginController struct {
beego.Controller
}
然后注冊路由:
修改router.go文件中的init()方法:
func init() { beego.Router("/", &controllers.MainController{},"get:Get;post:Post") beego.Router("/test", &controllers.TestController{},"get:TestGet;post:TestPost") beego.Router("/testinput", &controllers.TestInputController{},"get:TestInputGet;post:TestInputPost") beego.Router("/testlogin", &controllers.TestLoginController{},"get:Login;post:Post") }
然后再testlogin.go文件中添加一個Post()方法,用於用戶首次登錄,並設置Cookie:
type UserInfo struct { Username string //對應表單中的name值,字段名首字母也必須大寫,否則無法解析該參數的值 Password string `form:"pwd"` //也可以指定form表單中對應的name值,如果不寫將無法解析該參數的值 } func (c *TestLoginController) Post() { u := UserInfo{} if err := c.ParseForm(&u); err != nil { log.Panic(err) } fmt.Println("Post()方法中:username:",u.Username,",password:",u.Password) //設置cookie c.Ctx.SetCookie("username",u.Username,100,"/") c.Ctx.SetCookie("password",u.Password,100,"/") c.Ctx.WriteString("Username:" + u.Username + ",Password:" + u.Password) }
SetCookie的第三個參數是時間,單位是秒 ,如果不設置時間,Cookie只在本次回話有效,默認存活時間為3600秒。第四個參數是Cookie設置路徑。
二、獲取Cookie
接下來添加Login()方法,用於客戶端直接輸入網址時get請求,此時我們需要獲取cookie,並驗證cookie是否有效:
func (c *TestLoginController) Login() { //獲取cookie username := c.Ctx.GetCookie("username") password := c.Ctx.GetCookie("password") fmt.Println("Login()方法中:username:",username,",password:",password) //驗證用戶名和密碼: if username != "" { c.Ctx.WriteString("Username:" + username + ",Password:" + password) } else { c.Ctx.WriteString(`<html><form action="http://127.0.0.1:9527/testlogin" method="post"> 用戶名:<input type ="text" name="Username" /> <br/> 密   碼:<input type="password" name="pwd"> <br/> <input type="submit" value="提交"> </form></html>`) } }
如果cookie有效,我們直接在頁面顯示用戶名和密碼。否則我們跳轉到登錄頁面。
重啟項目,並打開瀏覽器輸入網址:http://127.0.0.1:9527/testlogin
第一次打開,效果如下:
此時經過get請求,執行對應的Login()方法,但是因為沒有cookie,所以執行else中的內容,顯示出登錄頁面。
然后我們輸入用戶名和密碼,點擊按鈕進行提交。此時通過post請求,執行對應的Post()方法,顯示登錄信息,並且設置cookie。
接下類,我們再次重新輸入地址:http://127.0.0.1:9527/testlogin。發現還是登錄成功頁面,因為經過get請求,執行Login()方法時,可以獲取到cookie,會直接顯示登錄信息,而無需用戶再次登錄了。
轉載地址: https://www.chaindesk.cn/witbook/17/282
謝謝原作者