beego實現使用者未登入跳轉到登入頁面
主要涉及內容:
- 自動路由
- 過濾器
- session控制
- 表單請求資料處理
main.go
//這裡應該載入 "github.com/astaxie/beego/context" 否則會載入src/context //過濾器 var FilterUser = func(ctx *context.Context){ _, ok := ctx.Input.Session("uid").(string) ok2 := strings.Contains(ctx.Request.RequestURI, "/login") if !ok && !ok2{ ctx.Redirect(302, "/login/index") } } func main() { //註冊過濾器 beego.InsertFilter("/*", beego.BeforeRouter, FilterUser) //開啟session beego.BConfig.WebConfig.Session.SessionOn = true setWebAutoRouter() beego.Run() } //註冊自動路由 func setWebAutoRouter(){ beego.AutoRouter(&controllers.TestController{}) beego.AutoRouter(&controllers.LoginController{}) }
loginController.go
type LoginController struct{ beego.Controller } type user struct { Id int `form:"-"` Name string `form:"username"` Age int `form:"age"` Email string } func (this *LoginController) Index(){ //獲取session值 this.Data["uid"] = this.GetSession("uid") this.TplName = "login.html" } func (this *LoginController) Register(){ u := user{} //處理表單提交的資料 if err := this.ParseForm(&u); err != nil{ fmt.Println(err) } else { //註冊session值 this.SetSession("uid", u.Name) } this.Data["uid"] = this.GetSession("uid") this.TplName = "login.html" }
testController.go
type TestController struct{ beego.Controller } func (this *TestController) Index(){ paramMap := this.Ctx.Input.Params() //獲取RESTFUL風格的引數 //此時的URL為 localhost:8080/test/index/aaa/bbb this.Data["Website"] = paramMap["0"]//aaa this.Data["Email"] = paramMap["1"]//bbb v := this.GetSession("uid") this.Data["uid"] = v.(string) this.TplName = "test.html" }
HTML程式碼略
參考網址:
https://beego.me/docs/intro/
https://www.jianshu.com/p/f583edfc7a1a