书接上回,上一回我们完成了用户办理页面的构建,而且通过前端的Vue.js框架动态地获取表单数据,同时异步恳求后端Iris接口停止入库操做,过程中利用函数封拆可复用的逻辑。 本回我们将继续完美用户办理功用。

独一索引

固然在之前的章节中已经完成了用户添加(注册)的功用,然而我们忽略了一个重要的细节,那就是用户名(username)应该是全局独一的字段,而添加逻辑中并未做独一性校验,事实上独一性校验有两种计划,一种是入库之前做一次查询,但如许会浪费一次磁盘的IO操做,别的一种就是通过独一索引停止拦截操做,那里我们接纳后者,修改model.go文件:

package modelimport ( "time" "github.com/jinzhu/gorm")tyPE Model struct { ID uint `gorm:"PRimary_key"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time}type User struct { gorm.Model Username string `gorm:"unique;not null"` Password string}

那里为User构造体的字段Username添加unique索引,随后将user表删除,从头停止数据库迁徙操做:

db.AutoMigrate(&model.User{})

接着查看表构造:

MySQL [irisblog]> SHOW CREATE TABLE user;+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| Table | Create Table |+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| user | CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, `deleted_at` datetime DEFAULT NULL, `username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`), KEY `idx_user_deleted_at` (`deleted_at`)) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+1 row in set (0.00 sec)

发现username字段已经被Gorm添加了独一索引:UNIQUE KEY `username` (`username`)

随后修改用户添加逻辑:

app.Post("/admin/user_action/", func(ctx iris.Context) { username := ctx.PostValue("username") password := ctx.PostValue("password") fmt.Println(username, password) md5str := mytool.Make_password(password) user := &model.User{Username: username, Password: md5str} res := db.Create(user) if res.Error != nil { fmt.Println(res.Error) ret := map[string]string{ "errcode": "1", "msg": "用户名不克不及反复", } ctx.JSON(ret) return } ret := map[string]string{ "errcode": "0", "msg": "ok", } ctx.JSON(ret) })

那里res构造体中的Error字段来返回错误,若是Error不等于nil,申明被独一索引拦截了下来。

随后构建 ret 字典,声明错误码和提醒信息,然后利用ctx.JSON函数序列化为Json格局返回给前端,留意别忘了用return关键字完毕逻辑,不然代码会继续施行,返回值样例:

{errcode: "1",msg: "用户名不克不及反复"}

前端领受到返回值之后,能够通过alert办法打印返回值:

submit:function(){ this.myaxios("http://localhost:5000/admin/user_action/","post",{"username":this.username,"password":this.password}).then(data => { console.log(data) alert(data.msg); }); }

如图所示:

Go语言进阶之Go语言高性能Web框架Iris项目实战-完美用户办理EP04  第1张

用户更新与删除

用户更新指的是密码的修改,起首需要构造新密码的表单变量:

data() { return { //用户名 username: "", //密码 password:"", //用户列表 userlist:[], //新密码 newpass:[] }; },

留意,那里是动态表单,因为每一个表单会对应一个用户:

for(let i=0,l=this.userlist.length;i<l;i++){ this.newpass.push({"value":""}) }

那里每返回一个用户,就会为该用户对应生成一个value字段。

随后在轮回中绑定该字段:

<table class="gridtable"> <tr> <th>用户id</th> <th>用户名</th> <th>新密码</th> <th>添加时间</th> <th>操做</th> </tr> <tr v-for="(item,index) in userlist"> <td>{{ item.ID }}</td> <td>{{ item.Username }}</td> <td><input type="password" v-model="newpass[index].value" /></td> <td>{{ item.CreatedAt }}</td> <td><button @click="update(index)">更新密码</button></td> </tr> </table>

如图所示:

Go语言进阶之Go语言高性能Web框架Iris项目实战-完美用户办理EP04  第2张

随后绑定单击事务,向后端iris传递参数:

update:function(i){ console.log(this.userlist[i].ID); console.log(this.newpass[i].value); if(this.newpass[i].value == ""){ alert("新密码不克不及为空"); return false; } this.myaxios("http://localhost:5000/admin/user_action/","put",{"id":this.userlist[i].ID,"password":this.newpass[i].value}).then(data => { console.log(data) alert(data.msg); }); }

那里传递的参数是用户id以及用户的新密码,留意恳求体例利用Put。

随后在后端Iris中添加更新逻辑:

app.Put("/admin/user_action/", func(ctx iris.Context) { ID := ctx.PostValue("id") Password := ctx.PostValue("password") user := &model.User{} db.First(&user, ID) user.Password = mytool.Make_password(Password) db.Save(&user) ret := map[string]string{ "errcode": "0", "msg": "更新密码胜利", } ctx.JSON(ret) })

那里利用Put函数监听路由,随后承受参数ID和Password,留意Put和Post体例都接纳ctx.PostValue函数来获取参数。

接着利用db.First(&user, ID)函数来停止主键查询,查出用户的构造体变量对象,最初挪用db.Save函数来存储更新成果:

MySQL [irisblog]> select * from user where id = 16\G*************************** 1. row *************************** id: 16created_at: 2022-08-22 19:41:40updated_at: 2022-08-23 15:41:09deleted_at: NULL username: admin password: 202cb962ac59075b964b07152d234b701 row in set (0.00 sec)MySQL [irisblog]>

能够看到,password和updated_at两个字段已经同步更新了。

接着是删除操做,起首前端添加删除按钮:

<tr v-for="(item,index) in userlist"> <td>{{ item.ID }}</td> <td>{{ item.Username }}</td> <td><input type="password" v-model="newpass[index].value" /></td> <td>{{ item.CreatedAt }}</td> <td> <button @click="update(index)">更新密码</button> <button @click="del(index)">删除用户</button> </td> </tr>

随后绑定删除事务:

del:function(i){ var r=confirm("您确定要删除吗?"); if (r==true){ this.myaxios("http://localhost:5000/admin/user_action/","delete",{"id":this.userlist[i].ID}).then(data => { console.log(data) alert(data.msg); }); } },

留意那里的恳求体例是delete。

如图所示:

Go语言进阶之Go语言高性能Web框架Iris项目实战-完美用户办理EP04  第3张

随后编写后端删除逻辑:

app.Delete("/admin/user_action/", func(ctx iris.Context) { ID := ctx.URLParamIntDefault("id", 0) db.Delete(&model.User{}, ID) ret := map[string]string{ "errcode": "0", "msg": "删除用户胜利", } ctx.JSON(ret) })

那里利用Delete函数来监听路由,同时通过ctx.URLParamIntDefault函数获取前端恳求的参数,留意Get和Delete体例获取参数的恳求函数是一致的,同理,Post体例和Put体例也是不异的。

接着利用db.Delete(&model.User{}, ID)函数通过用户构造体做主键删除。

结语

至此,完成了用户构造体的增:用户添加(独一索引拦截);删(主键删除);改(动态表单绑定修改密码);查(构造体单项和批量查询)。该项目已开源在Github:https://github.com/zcxey2911/IrisBlog ,与君共觞,和君共勉。