文章目錄
寫在前面
1. 建立商品
1.1 路由接口注冊
1.2 接口函數編寫
1.2.1 service層
1.2.2 api層
1.3 服務函數編寫
1.4 驗證服務
與前一章一樣,我們這個步驟也是需要jwt鑒權的,因為你要知道是誰建立了商品,是以我們要在請求頭上加上 token 連同 data 的資訊一起傳來建立商品
post 請求
authed.POST("product", api.CreateProduct)
定義一個建立商品的服務結構體
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 {
...
}
定義建立商品的對象
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)
編寫建立商品的服務函數
驗證使用者
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)
1
建構商品對象
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),
}
發送請求
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SM4MDNiBzYycTYzMGNldTOwUmZ0EGM2MTNwkDNjZDNj9CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
請求響應