【Go Actual | E-commerce Platform】(11) Update Products

1. Update the product

1.1 Routing interface registration

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

1.2 Writing interface functions

1.2.1 service layer

  • Create a service to update an item
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"`
}
  • How to create an updated product service
func (service *UpdateProductService) Update(id string) serializer.Response {
    
    
	...
}

1.2.2 api layers

  • Create an object that updates the commodity service
updateProductService := service.UpdateProductService{
    
    }
  • Context binding updates the commodity service object
c.ShouldBind(&updateProductService)
  • Call this method of updating the service object, note that this idis the one above the routeid
res := updateProductService.Update(c.Param("id"))
  • context return
c.JSON(200, res)
  • full code
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 Writing service functions

  • find product category
	var category model.Category
	model.DB.Model(&model.Category{
    
    }).First(&category,service.CategoryID)
  • find this item
	var product model.Product
	model.DB.Model(&model.Product{
    
    }).First(&product,id)
  • Modify product information
	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
  • save in database
err := model.DB.Save(&product).Error
  • returned messages
	return serializer.Response{
    
    
		Status: code,
		Msg:    e.GetMsg(code),
	}

1.4 Authentication Service

  • send request

insert image description here

  • response returned

insert image description here

Guess you like

Origin blog.csdn.net/weixin_45304503/article/details/121551904