Gin(六):文件上传

之前使用了数据库做了简单的增加和查询功能,今天再次使用数据库完成一些其他功能,比如说头像的上传和显示。

?新增用户头像

当用户登录完成后,页面右上角会显示当前用户的用户 email 。下面我们做点击 email 进入用户详情页,并可以修改信息。

先完善后端接口。通过用户的 id 来获取用户的详细信息,同时我们写了一个错误页 error.tmpl,来进行错误信息的展示。

userHandler.go

func UserProfile(context *gin.Context) {
   
	id := context.Query("id")
	var user model.UserModel
	i, err := strconv.Atoi(id)
	u, e := user.QueryById(i)
	if e != nil || err != nil {
   
		context.HTML(http.StatusOK, "error.tmpl", gin.H{
   
			"error": e,
		})
	}
	context.HTML(http.StatusOK, "user_profile.tmpl", gin.H{
   
		"user": u,
	})
}

代码中获取前端传递的id,通过 strconv.Atoi() 将String 类型转化为 int 类型。user.QueryById() 方法是我们用来进行对id查询的方法。

在进行 QueryById 方法之前,我们要对 user 结构体和数据库进行一下简单的修改。

type UserModel struct {
   
	Id       int            `form:"id"`
	Email    string         `form:"email" binding:"email"`
	Password string         `form:"password" `
	Avatar   sql.NullString
}

我们新增一行 Avatar ,类型为 sql.NullString 。为什么是 sql.NullString ?因为我们数据库中该字段初始时为 null ,而 string 类型是不可以接收 null 类型的,所以我们只能采用 NullString 来对 null 字符串进行处理。

同时,要对数据库进行添加,新增一列 avatar 字段。

修改后数据库

create table user
(
	id int auto_increment
		primary key,
	email varchar(30) not null,
	password varchar(40) not null,
	avatar varchar(100) null
)
comment '用户表';

完成前期的修改工作,可以做剩下的事情。

?️‍获取用户信息

userModel.go 中获取用户信息,完成 QueryById 方法

func (user *UserModel) QueryById(id int) (UserModel, error) {
   
	u := UserModel{
   }
	row := initDB.Db.QueryRow("select * from user where id = ?;", id)
	e := row.Scan(&u.Id, &u.Email, &u.Password, &u.Avatar)
	if e != nil {
   
		log.Panicln(e)
	}
	return u, e
}

该方法基本和上一节的通过邮箱查询用户方法基本一致。

完成该方法后,就可以将我们的路由添加上。

userRouter.GET("/profile/", handler.UserProfile)

此时就完成了后台的工作,剩下来就是对前端进行修改。

首先要重写划分一下前端的代码块。

template
|
|-error.tmpl
|-header.tmpl
|-index.tmpl
|-login.tmpl
|-nav.tmpl
|-user_profile.tmpl

我们将原来 indexhead 标签部分的代码移动到 header 中,将 header 原有的代码移动到 nav.tmpl 中。

index.tmpl

{
  {template "header"}}
<header>
    {
  {template "nav" .}}
</header>
<main>

</main>

header.tmpl

{
  { define "header" }}
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset=
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值