【Go实战 电商平台】(8) 创建商品 写在前面 1

这是我参与11月更文挑战的第28天,活动详情查看:2021最后一次更文挑战

写在前面

与前一章一样,我们这个步骤也是需要jwt鉴权的,因为你要知道是谁创建了商品,所以我们要在请求头上加上 token 连同 data 的信息一起传来创建商品

  1. 创建商品

1.1 路由接口注册

  • post 请求
1
go复制代码authed.POST("product", api.CreateProduct)

1.2 接口函数编写

1.2.1 service层

  • 定义一个创建商品的服务结构体
1
2
3
4
5
6
7
8
9
go复制代码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是上传者的idfilefileSize 是上传的商品图片以及其图片大小。

1
2
3
go复制代码func (service *CreateProductService)Create(id uint,file multipart.File,fileSize int64) serializer.Response {
...
}

1.2.2 api层

  • 定义创建商品的对象
1
go复制代码createProductService := service.CreateProductService{}
  • 获取token,并解析当前对象的id
1
go复制代码claim ,_ := util.ParseToken(c.GetHeader("Authorization"))
  • 获取传送过来的文件
1
go复制代码file , fileHeader ,_ := c.Request.FormFile("file")
  • 绑定上下文数据
1
go复制代码c.ShouldBind(&createProductService)
  • 执行创建对象下的create()方法,传入用户的id文件以及文件大小
1
go复制代码res := createProductService.Create(claim.ID,file,fileSize)

1.3 服务函数编写

编写创建商品的服务函数

  • 验证用户
1
2
go复制代码	var boss model.User
model.DB.Model(&model.User{}).First(&boss,id)
  • 上传图片到七牛云
1
2
3
4
5
6
7
8
go复制代码status , info := util.UploadToQiNiu(file,fileSize)
if status != 200 {
return serializer.Response{
Status: status ,
Data: e.GetMsg(status),
Error:info,
}
}
  • 获取分类
1
go复制代码model.DB.Model(&model.Category{}).First(&category,service.CategoryID)
  • 构建商品对象
1
2
3
4
5
6
7
8
9
10
11
12
13
go复制代码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,
}
  • 在数据库中创建
1
2
3
4
5
6
7
8
9
10
go复制代码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(),
}
}
  • 返回序列化的商品信息
1
2
3
4
5
go复制代码	return serializer.Response{
Status: code,
Data: serializer.BuildProduct(product),
Msg: e.GetMsg(code),
}

1.4 验证服务

  • 发送请求

在这里插入图片描述

  • 请求响应

在这里插入图片描述

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%