Beego学习(三)session和cookie

文章目录


简单例子
先访问:http://127.0.0.1:8001/test/login
填写内容后,点击提交
再访问:http://127.0.0.1:8001/test/login
此时会重定向到http://127.0.0.1:8001 界面

type User struct {
	Name   string //`json:"username"`
	Passwd string //`json:"password"`
}
//首先验证cookie,存在则重定向,不存在则登录
func (t *TestControllers) TestGet() {
	name := t.Ctx.GetCookie("name")
	passwd := t.Ctx.GetCookie("passwd")
	if (name != "") && (passwd != "") {
		t.Ctx.Redirect(303, "http://127.0.0.1:8001")
		return
	}
	t.Ctx.WriteString(`<html><form action="http://127.0.0.1:8001/test/login" method="post">
												<input type="test" name="Name"/>
												<input type="password" name="Passwd"/>
												<input type="submit" value="提交"/>
										</form></html>`)
}
//数据解析成功则设置cookie
func (t *TestControllers) TestPost() {
	u := &User{}
	if err := t.ParseForm(u); err != nil {
		t.Ctx.Output.SetStatus(405)
		t.Ctx.Output.Body([]byte("offset is failed"))
		return
	}
	//key  value 过期时间 url
	//过期时间为-1 代表清除cookie
	t.Ctx.SetCookie("name", u.Name, 100, "/")
	t.Ctx.SetCookie("passwd", u.Passwd, 100, "/")
	t.Ctx.Output.JSON(u, false, false)
}

session用法大致相同,只是涉及到接口断言。

发布了53 篇原创文章 · 获赞 5 · 访问量 2309

猜你喜欢

转载自blog.csdn.net/qq_25490573/article/details/104077881
今日推荐