主要涉及内容:
1. 自动路由
2. 过滤器
3. session控制
4. 表单请求数据处理
main.go
```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
```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
```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
有疑问加站长微信联系(非本文作者))