版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_41147260/article/details/84644688
1、get方式获取参数
Get、POST 等方式的请求,beego 里面会自动解析这些数据。
比如一个登陆页面的实现
前端我们是Post,用户名和密码
<form class="login_form" name = "login"method = "post" action="/article/user">
<h1 class="login_title">用户登录</h1>
<input type="text" class="input_txt" name = "username">
<input type="password" class="input_txt" name = "password">
<input type="submit" value="登 录" class="input_sub">
</form>
后端,我们使用下面这个方法来获取这些数据
- GetString(key string) string
- GetStrings(key string) []string
- GetInt(key string) (int64, error)
- GetBool(key string) (bool, error)
- GetFloat(key string) (float64, error)
2、解析到Struct
就是将表单里面的内容直接解析到一个struct中,完成数据的POST
这里,我们使用相同的前端页面
后端,我们需要新建一个struct去接收前端的数据。
user:= struct {
Id int `form:"-"`
Name string `form:"username"`
Pwd string `form:"password"`
}{}
- 定义 struct 时,字段名后如果有 form 这个 tag,则会以把 form 表单里的 name 和 tag 的名称一样的字段赋值给这个字段,否则就会把 form 表单里与字段名一样的表单内容赋值给这个字段。如上面例子中,会把表单中的 username 和 age 分别赋值给 user 里的 Name 和 Age 字段。
- 调用 Controller ParseForm 这个方法的时候,传入的参数必须为一个 struct 的指针,否则对 struct 的赋值不会成功并返回
xx must be a struct pointer
的错误。 - 如果要忽略一个字段,有两种办法,一是:字段名小写开头,二是:
form
标签的值设置为-
Controller中解析:
func (c *MainController) Post() {
u := user{}
if err := c.ParseForm(&u); err != nil {
//handle error
}
}
3、获取JSON / Request Body 里的内容
在企业中,我们用的更多的是API开发,而API中的数据经常会用到 JSON
或 XML
来作为数据交互的格式。这是如何实现的交互,我们来感受一下。
- 在配置文件里设置 copyrequestbody = true
- 在 Controller 中
- json 用来解析JSON的包
- ob定义的struct
func (this *ObjectController) Post() {
var ob models.Object
json.Unmarshal(this.Ctx.Input.RequestBody, &ob)
objectid := models.AddOne(ob)
this.Data["json"] = "{\"ObjectId\":\"" + objectid + "\"}"
this.ServeJSON()
}
例如获取一个数据表的json值
获取结果如下图