Beego controller 笔记
1、配置 web.BConfig 只是默认的那些配置项目。web.AppConfig. 可以所有项目; include "app2.conf" 可以包含其他文件。
App配置: AppName RunMode RecoverPanic
Web配置:StaticDir EnableXSRF web.BConfig.WebConfig
Session配置:web.BConfig.WebConfig.Session
Log配置:web.BConfig.Log.FileLineNum = true
2、路由
web.Router("/simple",&SimpleController{},"*:AllFunc;post:PostFunc")
namespace:
//初始化 namespace
ns :=
web.NewNamespace("/v1",
web.NSCond(func(ctx *context.Context) bool {
if ctx.Input.Domain() == "api.beego.me" {
return true
}
return false
}),
web.NSBefore(auth),
web.NSGet("/notallowed", func(ctx *context.Context) {
ctx.Output.Body([]byte("notAllowed"))
}),
web.NSRouter("/version", &AdminController{}, "get:ShowAPIVersion"),
web.NSRouter("/changepassword", &UserController{}),
web.NSNamespace("/shop",
web.NSBefore(sentry),
web.NSGet("/:id", func(ctx *context.Context) {
ctx.Output.Body([]byte("notAllowed"))
}),
),
web.NSNamespace("/cms",
web.NSInclude(
&controllers.MainController{},
&controllers.CMSController{},
&controllers.BlockController{},
),
),
)
//注册 namespace
web.AddNamespace(ns)
3、控制器介绍
type xxxController struct {
web.Controller
}
Prepare() Method 方法之前执行 Finish() Method 方法之后执行的
Redirect(url string, code int) 重定向。url是目的地址。
GetSession(name interface{}) interface{} 从Session中读取值。
SetSession(name interface{}, value interface{}) error 往Session中设置值。
DelSession(name interface{}) error 从Session中删除某项。
DestroySession() error 销毁Session
IsAjax() bool 是否是 Ajax 请求
XSRFToken() string 创建一个CSRF token.
StopRun() 直接触发panic
ServeXXX(encoding …bool) error 返回特性类型的响应。目前我们支持 JSON,JSONP,XML,YAML。
func (this *AddController) Get() {this.Data["content"] = "value"this.Layout = "admin/layout.html"this.TplName = "admin/add.tpl"}
func (this *AddController) Post() {pkgname := this.GetString("pkgname")content := this.GetString("content")。。。。。。this.Ctx.Redirect(302, "/admin/index")}
type NestPreparer interface {NestPrepare()}func (this *baseController) Prepare() {// page start timethis.Data["PageStartTime"] = time.Now()if app, ok := this.AppController.(NestPreparer); ok {app.NestPrepare()}}type BaseAdminRouter struct {baseController}func (this *BaseAdminRouter) NestPrepare() {if this.CheckActiveRedirect() {return}// if user isn't admin, then logout userif !this.user.IsAdmin {this.Redirect("/login", 302)return}// current in admin pagethis.Data["IsAdmin"] = trueif app, ok := this.AppController.(ModelPreparer); ok {app.ModelPrepare()return}}type RController struct {beego.Controller}func (this *RController) Prepare() {this.Data["json"] = map[string]interface{}{"name": "astaxie"}this.ServeJSON()this.StopRun() //调用 StopRun 之后,如果你还定义了 Finish 函数就不会再执行,如果需要释放资源}
4、请求数据处理
GetString(key string) string
GetStrings(key string) []string
GetInt(key string) (int64, error)
GetBool(key string) (bool, error)
GetFloat(key string) (float64, error)
如果你需要的数据可能是其他类型的,例如是 int 类型而不是 int64,那么你需要这样处理:
func (this *MainController) Post() {
id := this.Input().Get("id")
intid, err := strconv.Atoi(id)
}直接解析到 struct
func (this *MainController) Post() {u := user{}if err := this.ParseForm(&u); err != nil {//handle error}}
获取 Request Body 里的内容 if err = json.Unmarshal(this.Ctx.Input.RequestBody, &ob); err == nil { //配置文件里设置 copyrequestbody = true文件上传
func (c *FormController) Post() {f, h, err := c.GetFile("uploadname")if err != nil {log.Fatal("getfile err ", err)}defer f.Close()c.SaveToFile("uploadname", "static/upload/" + h.Filename) // 保存位置在 static/upload, 没有文件夹要先创建}
数据绑定
?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie
var id int
this.Ctx.Input.Bind(&id, "id") //id ==123
var isok bool
this.Ctx.Input.Bind(&isok, "isok") //isok ==true
var ft float64
this.Ctx.Input.Bind(&ft, "ft") //ft ==1.2
ol := make([]int, 0, 2)
this.Ctx.Input.Bind(&ol, "ol") //ol ==[1 2]
ul := make([]string, 0, 2)
this.Ctx.Input.Bind(&ul, "ul") //ul ==[str array]
user struct{Name}
this.Ctx.Input.Bind(&user, "user") //user =={Name:"astaxie"}
5、session 控制
beego 中使用 session 相当方便,只要在 main 入口函数中设置如下:
web.BConfig.WebConfig.Session.SessionOn = true
或者通过配置文件配置如下:
复制代码sessionon = true
web.BConfig.WebConfig.Session.SessionGCMaxLifetime
设置 Session 过期的时间,默认值是 3600 秒,配置文件对应的参数:sessiongcmaxlifetime。
当 SessionProvider 为 redis 时,SessionProviderConfig 是 redis 的链接地址,采用了 redigo,如下所示:
web.BConfig.WebConfig.Session.SessionProvider = "redis"web.BConfig.WebConfig.Session.SessionProviderConfig = "127.0.0.1:6379"
6、过滤器 beego 支持自定义过滤中间件,例如安全验证,强制跳转等。
web.InsertFilter(pattern string, pos int, filter FilterFunc, opts ...FilterOpt)
position:
BeforeStatic 静态地址之前
BeforeRouter 寻找路由之前
BeforeExec 找到路由之后,开始执行相应的 Controller 之前
AfterExec 执行完 Controller 逻辑之后执行的过滤器
FinishRouter 执行完逻辑之后执行的过滤器
var FilterUser = func(ctx *context.Context) {_, ok := ctx.Input.Session("uid").(int)if !ok && ctx.Request.RequestURI != "/login" {ctx.Redirect(302, "/login")}}web.InsertFilter("/*", web.BeforeRouter, FilterUser)
7、表单数据验证
u := User{"man", 40}valid := validation.Validation{}valid.Required(u.Name, "name")valid.MaxSize(u.Name, 15, "nameMax")valid.Range(u.Age, 0, 18, "age")if valid.HasErrors() {// 如果有错误信息,证明验证没通过// 打印错误信息for _, err := range valid.Errors {log.Println(err.Key, err.Message)}}// or use like thisif v := valid.Max(u.Age, 140, "age"); !v.Ok {log.Println(v.Error.Key, v.Error.Message)}// 定制错误信息minAge := 18valid.Min(u.Age, minAge, "age").Message("少儿不宜!")// 错误信息格式化valid.Min(u.Age, minAge, "age").Message("%d不禁", minAge)
Match(pattern string)正则匹配,有效类型:string,其他类型都将被转成字符串再匹配(fmt.Sprintf(“%v”, obj).Match)
版权声明本文仅代表作者观点,不代表本站立场。本文系作者授权发表,未经许可,不得转载。图文来源网络,侵权删!