1.Controller基本使用
基于 beego 的 Controller 设计,只需要匿名组合 beego.Controller 就可以了,如下所示:


beego.Controller 拥有很多方法,其中包括 Init、Prepare、Post、Get、Delete、Head等 方法。我们可以通过重写的方式来实现这些方法,而我们上面的代码就是重写了 Get 方法。
我们可以通过各种方式获取数据,然后赋值到 this.Data 中,这是一个用来存储输出数据的 map,可以赋值任意类型的值,这里我们只是简单举例输出两个字符串。
最后一个就是需要去渲染的模板,this.TplName 就是需要渲染的模板,这里指定了 index.tpl,如果用户不设置该参数,那么默认会去到模板目录的 Controller/<方法名>.tpl 查找,例如上面的方法会去 maincontroller/get.tpl(文件、文件夹必须小写)。
用户设置了模板之后系统会自动的调用 Render 函数(这个函数是在 beego.Controller 中实现的),所以无需用户自己来调用渲染。
示例:
这里我直接写了一个TestController

然后再路由进行设置,就可以在浏览器中直接访问了


2.Controller请求数据处理
1.通过get获取参数



2.通过结构体获取参数,此处演示Post提交表单



3.获取 Request Body 里的内容
- 在配置文件里设置 copyrequestbody = true
-
在 Controller 中
image.png
网友评论