这是我参与11月更文挑战的第28天,活动详情查看:2021最后一次更文挑战
写在前面
与前一章一样,我们这个步骤也是需要jwt鉴权的,因为你要知道是谁创建了商品,所以我们要在请求头上加上 token 连同 data 的信息一起传来创建商品
1. 创建商品
1.1 路由接口注册
- post 请求
authed.POST("product", api.CreateProduct)
1.2 接口函数编写
1.2.1 service层
- 定义一个创建商品的服务结构体
type CreateProductService struct {
Name string `form:"name" json:"name"`
CategoryID int `form:"category_id" json:"category_id"`
Title string `form:"title" json:"title" bind:"required,min=2,max=100"`
Info string `form:"info" json:"info" bind:"max=1000"`
ImgPath string `form:"img_path" json:"img_path"`
Price string `form:"price" json:"price"`
DiscountPrice string `form:"discount_price" json:"discount_price"`
}
- 定义一个创建商品的
create
方法
传入进来的有id
是上传者的id
,file
和fileSize
是上传的商品图片以及其图片大小。
func (service *CreateProductService)Create(id uint,file multipart.File,fileSize int64) serializer.Response {
...
}
1.2.2 api层
- 定义创建商品的对象
createProductService := service.CreateProductService{}
- 获取token,并解析当前对象的id
claim ,_ := util.ParseToken(c.GetHeader("Authorization"))
- 获取传送过来的文件
file , fileHeader ,_ := c.Request.FormFile("file")
- 绑定上下文数据
c.ShouldBind(&createProductService)
- 执行创建对象下的
create()
方法,传入用户的id
,文件
以及文件大小
等
res := createProductService.Create(claim.ID,file,fileSize)
1.3 服务函数编写
编写创建商品的服务函数
- 验证用户
var boss model.User
model.DB.Model(&model.User{}).First(&boss,id)
- 上传图片到七牛云
status , info := util.UploadToQiNiu(file,fileSize)
if status != 200 {
return serializer.Response{
Status: status ,
Data: e.GetMsg(status),
Error:info,
}
}
- 获取分类
model.DB.Model(&model.Category{}).First(&category,service.CategoryID)
- 构建商品对象
product := model.Product{
Name: service.Name,
Category: category,
CategoryID: uint(service.CategoryID),
Title: service.Title,
Info: service.Info,
ImgPath: info,
Price: service.Price,
DiscountPrice: service.DiscountPrice,
BossID: int(id),
BossName: boss.UserName,
BossAvatar: boss.Avatar,
}
- 在数据库中创建
err := model.DB.Create(&product).Error
if err != nil {
logging.Info(err)
code = e.ErrorDatabase
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
Error: err.Error(),
}
}
- 返回序列化的商品信息
return serializer.Response{
Status: code,
Data: serializer.BuildProduct(product),
Msg: e.GetMsg(code),
}
1.4 验证服务
- 发送请求
- 请求响应