Beego—获取表单数据和表单数据解析到结构体
获取表单数据
在前面第五章我们演示了用表单获取登录数据。
现在我们再来详细的模拟下注册信息的获取。
首先新建一个注册register模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action="/register" method="post">
<table>
<tbody>
<tr>
<td>用户名</td>
<td>
<input type="text" name ="Name" value="">
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name ="Pwd" value="">
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name ="Sex" value="man"checked="checked">男
<input type="radio" name ="Sex" value="woman">女
</td>
</tr>
<tr>
<td>年龄</td>
<td>
<input type="text" name ="Age" value="">
</td>
</tr>
<tr>
<td>
<input type="submit" value="确认">
</td>
<td>
<input type="reset" value="重置">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
从上面的html代码中我们可以看出我们提交到/register 提交方式依然为post。 用户名、密码、性别、年龄的name属性分别为:Name、Pwd、Sex、Age。
效果图:

接下来我们写实现代码:
type RegController struct {
beego.Controller
}
func (this *RegController)Get() {
this.TplName ="register.html"
}
func (this *RegController)Post1() {
Name:=this.GetString("Name")
Pwd:=this.GetString("Pwd")
Sex:=this.GetString("Sex")
Age,err:=this.GetInt("Age")
if err==nil {
this.Ctx.WriteString("Name="+Name+"\nPwd="+Pwd+"\nSex="+Sex+"\nAge="+strconv.Itoa(Age))
}else{
this.Ctx.WriteString("Name="+Name+"\nPwd="+Pwd+"\nSex="+Sex)
}
}
从上面代码,可以看到Get方法 用来解析register.html 模板, Post方法用来获取数据。然后我们重点看下Post方法。我们可以看到GetString里面的参数和我们刚刚表单设置的name属性 一模一样。(注意:名字必须一模一样,为了避免坑大小写都要相同)
注册路由:
beego.Router("/register",&controllers.RegController{})
如果不写方法,路由会自动帮我们调用Get和Post方法 。
我们现在输入http://localhost:8080/register来运行项目
输出结果:

-
解析到结构体
我们首先定义一个结构体:
type Users struct {
Name string
Pwd string
Age int
Sex string
}

然后实现功能:
func (this *RegController)Get() {
this.TplName ="register.html"
}
func (this *RegController)Post() {
var user Users
if error:=this.ParseForm(&user);error!=nil {
this.Ctx.WriteString("出错了!")
}else{
this.Ctx.WriteString("我是结构体\n")
this.Ctx.WriteString("Name="+user.Name+"\nPwd="+user.Pwd+"\nSex="+user.Sex+"\nAge="+strconv.Itoa(user.Age))
}
}
Get方法没有任何变化,依然是用来解析模板。beego提供了ParseForm方法用来解析表单数据。调用ParseForm 这个方法的时候,传入的参数必须为一个 struct 的指针,否则对 struct 的赋值不会成功并返回xx must be a struct pointer
的错误
输出结果:

如果我们不想解析某个属性,我们可以使用Tag 在属性添加form:"-"
,还有一种方法就是开头字母小写。
使用Tag
type Users struct {
Name string `form:"name"`
Pwd string
Age int `form:"-"`
Sex string
}
我们也可以使用Tag给属性设置别名.它可以让结构体属性对应到表单中的name ,当然 from后面的字段必须要和对应表单中的name大小写完全一样。
比如说我们表单中的<input type="text" name ="name" value=""> name首字母是小写,但是结构体的属性Name必须是大写,不然就解析不到。这时候如果我们在不需要更改表单name的情况下,就要用到from来对应。