【Go实战 | 电商平台】(11) 更新商品

文章目录

1. 更新商品

1.1 路由接口注册

1.2 接口函数编写

1.2.1 service层

1.2.2 api层

1.3 服务函数编写

1.4 验证服务

1. 更新商品

1.1 路由接口注册

authed.PUT("product/:id", api.UpdateProduct)


1.2 接口函数编写

1.2.1 service层

创建更新商品的服务

type UpdateProductService struct {
    ID            uint   `form:"id" json:"id"`
    Name          string `form:"name" json:"name"`
    CategoryID    int    `form:"category_id" json:"category_id"`
    Title         string `form:"title" json:"title" binding:"required,min=2,max=100"`
    Info          string `form:"info" json:"info" binding:"max=1000"`
    ImgPath       string `form:"img_path" json:"img_path"`
    Price         string `form:"price" json:"price"`
    DiscountPrice string `form:"discount_price" json:"discount_price"`
    OnSale bool `form:"on_sale" json:"on_sale"`
    Num string `form:"num" json:"num"`
}


创建更新的商品服务的方法

func (service *UpdateProductService) Update(id string) serializer.Response {
    ...
}


1.2.2 api层

创建一个更新商品服务的对象

updateProductService := service.UpdateProductService{}


上下文绑定更新商品服务对象

c.ShouldBind(&updateProductService)


调用这个更新服务对象的方法,注意这个id是路由上面的那个id

res := updateProductService.Update(c.Param("id"))


上下文返回

c.JSON(200, res)


完整代码

func UpdateProduct(c *gin.Context) {
    updateProductService := service.UpdateProductService{}
    if err := c.ShouldBind(&updateProductService); err == nil {
  res := updateProductService.Update(c.Param("id"))
  c.JSON(200, res)
    } else {
  c.JSON(200, ErrorResponse(err))
  logging.Info(err)
    }
}


1.3 服务函数编写

找到商品分类

var category model.Category
    model.DB.Model(&model.Category{}).First(&category,service.CategoryID)


找到该商品

var product model.Product
    model.DB.Model(&model.Product{}).First(&product,id)

修改商品信息

product.Name=service.Name
    product.Category=category
    product.CategoryID=uint(service.CategoryID)
    product.Title=service.Title
    product.Info=service.Info
    product.ImgPath=service.ImgPath
    product.Price=service.Price
    product.DiscountPrice=service.DiscountPrice
    product.OnSale=service.OnSale


保存数据库中

err := model.DB.Save(&product).Error


返回信息

return serializer.Response{
  Status: code,
  Msg:    e.GetMsg(code),
    }

1.4 验证服务

发送请求

【Go实战 | 电商平台】(11) 更新商品


响应返回

【Go实战 | 电商平台】(11) 更新商品


上一篇:【Go实战 | 电商平台】(10) 搜索商品


下一篇:【Go实战 | 电商平台】(12) 删除商品