【Go实战 | 电商平台】(8) 创建商品

这是我参与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是上传者的idfilefileSize 是上传的商品图片以及其图片大小。

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 验证服务

  • 发送请求

在这里插入图片描述

  • 请求响应

在这里插入图片描述

Guess you like

Origin juejin.im/post/7035422989797556260