管理员登陆功能后端

DAO层:

type Admin struct {
	Id        int       `json:"id" gorm:"primary_key" description:"自增主键"`
	UserName  string    `json:"user_name" gorm:"column:user_name" description:"管理员用户名"`
	Salt      string    `json:"salt" gorm:"column:salt" description:"盐"`
	Password  string    `json:"password" gorm:"column:password" description:"密码"`
	UpdatedAt time.Time `json:"update_at" gorm:"column:update_at" description:"更新时间"`
	CreatedAt time.Time `json:"create_at" gorm:"column:create_at" description:"创建时间"`
	IsDelete  int       `json:"is_delete" gorm:"column:is_delete" description:"是否删除"`
}
注释字段含义
json定义json转换后的名字
gormgin 框架数据库连接池提供的 结构体中该属性在数据库中的字段名
descript字段描述

DTO层

type AdminLoginInput struct {
	UserName string `json:"username" form:"username" comment:"管理员用户名" example:"admin" validate:"required"` //管理员用户名
	Password string `json:"password" form:"password" comment:"密码" example:"123456" validate:"required"`    //密码
}
//验证输入数据是否符合校验规则 并将前端输入的数据json转化成结构体数据,为结构体赋值
func (param *AdminLoginInput) BindValidParam(c *gin.Context) error {
	return public.DefaultGetValidParams(c, param)
}

type AdminLoginOutput struct {
	Token string `json:"token" form:"token" comment:"token" example:"token" validate:""` //token
}

input结构体注释含义

注释字段含义
json定义json转换后的名字
form表单中字段的名字
comment字段描述
example默认数据
validate验证器名

output结构体为什么要用 token类型 json的返回 :
当前端需要向服务器请求数据时,服务器需要频繁的向数据库查询用户名和密码是否正确,这就使服务器压力变大,Token是服务器生成的一串字符串,作为前端向服务器进行请求的一个令牌,当第一次登陆成功时,服务器生成一个Token便将此Token返回给客户端,以后客户端只需带上这个Token前来请求数据即可,无需再次带上用户名和密码。这样就减轻服务器的压力,减少频繁的查询数据库,使服务器更加健壮。

Controller 层

在没有做好前端页面之前,为了验证服务器定义的接收请求的方法是否有效,我们一般会配合swagger文档进行使用,gin scaffold 框架支持swagger文档,只需要在请求的方法前,按规则填写好注释就行,注释格式大概如下:

// ListPage godoc
// @Summary 管理员登陆
// @Description 管理员登陆
// @Tags 管理员接口
// @ID /admin_login/login
// @Accept  json
// @Produce  json
// @Param body body dto.AdminLoginInput true "body"
// @Success 200 {object} middleware.Response{data=dto.AdminLoginOutput} "success"
// @Router /admin_login/login [post]

swag initgo run main.go

路由注册

xxxRouter:=router.Group("/xxx")xxxRouter.Use(sessions.Sessions("mysession", store), middleware.RecoveryMiddleware(), middleware.RequestLog(), middleware.SessionAuthMiddleware(), middleware.TranslationMiddleware())controller.xxxRegister(xxxRouter)

xxxRegister方法的定义如下:

type xxxController struct{}

func xxxRegister(group *gin.RouterGroup) {
  xxx := &xxxController{}
  group.GET("/yyy", xxx.funcname)
}

当请求路径为xxx/yyy时,就会用 xxx.funcname()来对请求数据进行处理