一.新建商品
1. 配置路由
goods-web/router/goods.go
package router import ( "github.com/gin-gonic/gin" "mxshop-api/goods-web/api/goods" ) func InitGoodsRoute(Router *gin.RouterGroup) { GoodsRouter := Router.Group("goods") { GoodsRouter.GET("list", goods.List) //GoodsRouter.GET("new", middlewares.JWTAuth(), middlewares.IsAdminAuth(), goods.New) GoodsRouter.POST("new", goods.New) } }
2.配置form验证
goods-web/forms/goods.go
package forms type GoodsForm struct { Name string `form:"name" json:"name" binding:"required,min=2,max=100"` GoodsSn string `form:"goods_sn" json:"goods_sn" binding:"required,min=2,lt=20"` Stocks int32 `form:"stocks" json:"stocks" binding:"required,min=1"` CategoryId int32 `form:"category" json:"category" binding:"required"` MarketPrice float32 `form:"market_price" json:"market_price" binding:"required,min=0"` ShopPrice float32 `form:"shop_price" json:"shop_price" binding:"required,min=0"` GoodsBrief string `form:"goods_brief" json:"goods_brief" binding:"required,min=3"` Images []string `form:"images" json:"images" binding:"required,min=1"` DescImages []string `form:"desc_images" json:"desc_images" binding:"required,min=1"` ShipFree *bool `form:"ship_free" json:"ship_free" binding:"required"` FrontImage string `form:"front_image" json:"front_image" binding:"required,url"` Brand int32 `form:"brand" json:"brand" binding:"required"` }
2.配置api函数
goods-web/api/goods/goods.go
func New(ctx *gin.Context) { goodsForm := forms.GoodsForm{} if err := ctx.ShouldBindJSON(&goodsForm); err != nil { HandleValidatorError(ctx, err) return } goodsClient := global.GoodsSrvClient rsp, err := goodsClient.CreateGoods(context.Background(), &proto.CreateGoodsInfo{ Name: goodsForm.Name, GoodsSn: goodsForm.GoodsSn, Stocks: goodsForm.Stocks, MarketPrice: goodsForm.MarketPrice, ShopPrice: goodsForm.ShopPrice, GoodsBrief: goodsForm.GoodsBrief, ShipFree: *goodsForm.ShipFree, Images: goodsForm.Images, DescImages: goodsForm.DescImages, GoodsFrontImage: goodsForm.FrontImage, CategoryId: goodsForm.CategoryId, BrandId: goodsForm.Brand, }) if err != nil { HandleGrpcErrorToHttp(err, ctx) return } //如何设置库存 //TODO 商品的库存 - 分布式事务 ctx.JSON(http.StatusOK, rsp) }
标签:web,goods,goodsForm,form,binding,required,改查,json,go From: https://www.cnblogs.com/wlike/p/16927447.html