1、Controller中数据参数处理
获取参数:
我们经常需要获取用户传递的数据,包括 Get、POST 等方式的请求,beego 里面会自动解析这些数据,你可以通过如下方式获取数据:
GetString(key string) string GetStrings(key string) []string GetInt(key string) (int64, error) GetBool(key string) (bool, error) GetFloat(key string) (float64, error)
示例:
func (this *MainController) Post() {
jsoninfo := this.GetString("jsoninfo")
if jsoninfo == "" {
this.Ctx.WriteString("jsoninfo is empty")
return
}
}
2、输入名称,直接显示出来
示例:
/routers/router.go
package routers import (
"web/controllers" "github.com/astaxie/beego"
) func init() {
beego.Router("/", &controllers.MainController{})
// beego.Router("/test", &controllers.TestInputController{}, "get:Get;post:Post")
beego.Router("/test_input", &controllers.TestInputController{}, "get:Get;post:Post")
}
controllers/testInput.go
package controllers import (
"github.com/astaxie/beego"
) type TestInputController struct {
beego.Controller
} type User struct {
Username string
Password string
} func (c *TestInputController) Get() {
id := c.GetString("id")
c.Ctx.WriteString("<html>" + id + "<br/>") name := c.Input().Get("name")
c.Ctx.WriteString(name + "</html>") }
执行结果:
#在浏览器中输入:
http://127.0.0.1:8080/test_input?id=nulige
结果:提交会报错。
3、输入用户名和密码直接提交,出结果。
示例:
/routers/router.go
package routers import (
"web/controllers" "github.com/astaxie/beego"
) func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test_input", &controllers.TestInputController{}, "get:Get;post:Post")
}
controllers/testInput.go
package controllers import (
"github.com/astaxie/beego"
) type TestInputController struct {
beego.Controller
} type User struct {
Username string
Password string
} func (c *TestInputController) Get() {
c.Ctx.WriteString(`<html><form action="http://127.0.0.1:8080/test_input" method="post">
<input type="text" name="Username"/>
<input type="password" name="Password"/>
<input type="submit" value="提交"/>
</form></html>`)
} func (c *TestInputController) Post() {
u := User{}
if err := c.ParseForm(&u); err != nil {
//process error
} c.Ctx.WriteString("Username:" + u.Username + " Password:" + u.Password)
}
执行结果:
#在浏览器中输入:
http://127.0.0.1:8080/test_input?id=nulige
输入: username: nulige, password: nulige
结果:
Username:nulige Password:nulige
4、获取Request Boby里的内容
- 在配置文件里设置 copyrequestbody = true
- 在 Controller 中
示例:
func (this *ObjectController) Post() {
var ob models.Object
json.Unmarsha1(this.Ctx.Input.RequestBody, &ob)
objectid := models.AddOne(ob)
this.Data["json"] = "{\"ObjectId\":\}"" + objectid + "\"}"
this.ServeJSON()
}