【Go】十八、http 调用服务的编写

http接口框架的搭建

这个http接口框架的搭建参考之前的全量搭建,这里是快速搭建的模式:

直接对已有的http模块进行复制修改,主要修改点在于 proto部分与api、router 部分,剩余的要针对进行修改模块名称。

接口的具体编写

在 api/goods/goods.go 中编写具体的代码:

例如:goods的List接口的开发:

func List(ctx *gin.Context) {request := &proto.GoodsFilterRequest{}priceMin := ctx.DefaultQuery("pmin", "0") // 取出设定的最小价格,默认为 0priceMinInt, _ := strconv.Atoi(priceMin)request.PriceMin = int32(priceMinInt)priceMax := ctx.DefaultQuery("pmax", "0")priceMaxInt, _ := strconv.Atoi(priceMax)request.PriceMax = int32(priceMaxInt)isHot := ctx.DefaultQuery("ih", "0")if isHot == "1" {request.IsHot = true}isNew := ctx.DefaultQuery("in", "0")if isNew == "1" {request.IsNew = true}isTab := ctx.DefaultQuery("it", "0")if isTab == "1" {request.IsTab = true}categoryId := ctx.DefaultQuery("c", "0")categoryIdInt, _ := strconv.Atoi(categoryId)request.TopCategory = int32(categoryIdInt)pages := ctx.DefaultQuery("p", "0")pagesInt, _ := strconv.Atoi(pages)request.Pages = int32(pagesInt)perNums := ctx.DefaultQuery("pnum", "0")perNumsInt, _ := strconv.Atoi(perNums)request.PagePerNums = int32(perNumsInt)keywords := ctx.DefaultQuery("q", "")request.KeyWords = keywordsbrandId := ctx.DefaultQuery("b", "0")brandIdInt, _ := strconv.Atoi(brandId)request.Brand = int32(brandIdInt)r, err := global.GoodsSrvClient.GoodsList(context.Background(), request)if err != nil {zap.S().Errorw("[List] 查询 【商品列表】 失败")HandleGrpcErrorToHttp(err, ctx)return}reMap := map[string]interface{}{"total": r.Total,"data":  r.Data,}ctx.JSON(http.StatusOK, reMap)
}

但是呢,这种写法存在一定的问题,就是在http接口中未存在对于 后端数据的修正,这样子不便于前端与后端的数据对接,所以我们在 http 端一般可以做一个修改确定:

	reMap := map[string]interface{}{"total": r.Total,}// 这里一般会进行数据处理goodsList := make([]interface{}, 0)for _, value := range r.Data {goodsList = append(goodsList, map[string]interface{}{"id":          value.Id,"name":        value.Name,"goods_brief": value.GoodsBrief,"desc":        value.GoodsDesc,"ship_free":   value.ShipFree,"images":      value.Images,"desc_images": value.DescImages,"front_image": value.GoodsFrontImage,"shop_price":  value.ShopPrice,"category": map[string]interface{}{"id":   value.Category.Id,"name": value.Category.Name,},"brand": map[string]interface{}{"id":   value.Brand.Id,"name": value.Brand.Name,"logo": value.Brand.Logo,},"is_hot":  value.IsHot,"is_new":  value.IsNew,"on_sale": value.OnSale,})}reMap["data"] = goodsListctx.JSON(http.StatusOK, reMap)

注册中心内容抽取

有时候,我们的项目不是完全基于某一个注册中心,我们不希望将注册中心的逻辑集成在 main文件中,我们希望我们的项目具有快速替换性,这个时候就需要我们将注册中心的内容抽取出来

注册中心服务注册

我们在 util 包下创建一个 register 包,再在 register包下创建 consul包,再在 consul包下创建register.go:

package consulimport ("fmt""github.com/hashicorp/consul/api""mxshop-api/goods-web/global"
)// 重新配置Register,令其单独拎出来
// 注册类,这是一个类
type Registry struct {Host stringPort int
}// 这个是类的能力,能干什么
type RegistryClient interface {Register(address string, port int, name string, tags []string, id string) errorDeRegister(serviceId string) error
}func NewRegistryClient(host string, port int) RegistryClient {return &Registry{Host: host,Port: port,}
}func (r *Registry) Register(address string, port int, name string, tags []string, id string) error {cfg := api.DefaultConfig()cfg.Address = fmt.Sprintf("%s:%d", r.Host, r.Port) // consul 的地址client, err := api.NewClient(cfg)if err != nil {panic(err)}// 生成 consul 的注册对象// 配置基础信息registration := new(api.AgentServiceRegistration)registration.Name = nameregistration.ID = idregistration.Tags = tagsregistration.Port = portregistration.Address = address// 配置检查对象,也就是健康检查机制check := &api.AgentServiceCheck{HTTP:                           fmt.Sprintf("http://%s:%d/health", global.ServerConfig.Host, global.ServerConfig.Port), // 发送 GET 请求来进行健康检查,服务的地址Timeout:                        "5s",                                                                                   // 每次健康检查中,多久没有回复视为健康检查失败Interval:                       "5s",                                                                                   // 进行健康检查的频率DeregisterCriticalServiceAfter: "10s",                                                                                  // 不健康服务允许存活的时间,当一个服务被检查为不健康时,若 10s 内其没有转为健康,则将其从服务中删除}// 将检查对象配置进 consul 的注册对象 registration 中registration.Check = check// 将配置的 consul 注册进去err = client.Agent().ServiceRegister(registration)client.Agent().ServiceDeregister(name)if err != nil {panic(err)}return nil}func (r *Registry) DeRegister(serviceId string) error {return nil
}

在这个程序中,我们要注意的是程序的注册与鸭子类型的实际应用,同时理解golang的设计思想

main.go

	// 动态配置 Consul 相关信息register_client := consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)serviceId := fmt.Sprintf("%s", uuid.NewV4())err := register_client.Register(global.ServerConfig.Host, global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, serviceId)if err != nil {zap.S().Panic("服务注册失败", err.Error())}

注册中心服务注销

优雅的利用go 的队列机制注销服务

	quit := make(chan os.Signal)// 如果接收到了 kill 或 ctrl C,则进入quitsignal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)<-quitif err = register_client.DeRegister(serviceId); err != nil {zap.S().Panic("注销失败:", err.Error())} else {zap.S().Panic("注销成功")}

新建商品接口

在router中添加路由,这个商品需要管理员权限才可以新建

func InitGoodsRouter(Router *gin.RouterGroup) {// 这样就需要 /user/list 才可以进行访问了GoodsRouter := Router.Group("goods"){// 在这里添加拦截器的作用响应位置GoodsRouter.GET("", goods.List)GoodsRouter.POST("", middlewares.JWTAuth(), middlewares.IsAdminAuth(), goods.New)}
}

同时我们在 api/goods.go 中添加新建商品的接口

func New(ctx *gin.Context) {// 由于这里使用了 类似于 Vo 的感觉,所以先构建一个用来绑定获取到的前端数据goodsForm := forms.GoodsForm{}// 绑定 ShouldBind可以同时绑定form和json,这里就写的明确一点,视为json形式if err := ctx.ShouldBindJSON(&goodsForm); err != nil {HandleValidatorError(ctx, err)return}// 利用proto 从 grpc服务中获取所需的信息goodsClient := global.GoodsSrvClientrsp, 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,GoodsDesc:       goodsForm.GoodsDesc,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)
}

商品详情接口

在 router 中创建 单独商品详情接口:

GoodsRouter.GET("/:id", goods.Detail) // 捕捉类似于/goods/123 的内容中的 123
func Detail(ctx *gin.Context) {// 获取拼接在 链接之后的参数id := ctx.Param("id") // 获取 /goods/123i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}// 发送 grpc 请求查询相关内容r, err := global.GoodsSrvClient.GetGoodsDetail(context.Background(), &proto.GoodInfoRequest{Id: int32(i),})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)}rsp := map[string]interface{}{"id":          r.Id,"name":        r.Name,"goods_brief": r.GoodsBrief,"desc":        r.GoodsDesc,"ship_free":   r.ShipFree,"images":      r.Images,"desc_images": r.DescImages,"front_image": r.GoodsFrontImage,"shop_price":  r.ShopPrice,"category": map[string]interface{}{"id":   r.Category.Id,"name": r.Category.Name,},"brand": map[string]interface{}{"id":   r.Brand.Id,"name": r.Brand.Name,"logo": r.Brand.Logo,},"is_hot":  r.IsHot,"is_new":  r.IsNew,"on_sale": r.OnSale,}ctx.JSON(http.StatusOK, rsp)
}

删除商品接口

在 router 中创建 删除商品的接口:

GoodsRouter.DELETE("/:id", middlewares.JWTAuth(), middlewares.IsAdminAuth(), goods.Delete)
func Delete(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}_, err = global.GoodsSrvClient.DeleteGoods(context.Background(), &proto.DeleteGoodsInfo{Id: int32(i)})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.Status(http.StatusOK)return
}

获取商品库存接口

库存接口正在开发中

在router 中新增接口

GoodsRouter.GET("/:id/stocks", goods.Stocks) // 获取商品库存
func Stocks(ctx *gin.Context) {id := ctx.Param("id")_, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}// TODO 商品库存相关信息
}

更新商品状态接口

GoodsRouter.PATCH("/:id", middlewares.JWTAuth(), middlewares.IsAdminAuth(), goods.UpdateStatus)
func UpdateStatus(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}goodsStatusForm := forms.GoodsStatusForm{}if err := ctx.ShouldBindJSON(&goodsStatusForm); err != nil {api.HandleValidatorError(ctx, err)return}if _, err = global.GoodsSrvClient.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{Id:     int32(i),IsNew:  *goodsStatusForm.IsNew,IsHot:  *goodsStatusForm.IsHot,OnSale: *goodsStatusForm.OnSale,}); err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.JSON(http.StatusOK, gin.H{"msg": "修改成功",})
}

更新商品接口

GoodsRouter.PUT("/:id", middlewares.JWTAuth(), middlewares.IsAdminAuth(), goods.Update)
func Update(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}goodsForm := forms.GoodsForm{}if err = ctx.ShouldBindJSON(&goodsForm); err != nil {api.HandleValidatorError(ctx, err)return}if _, err = global.GoodsSrvClient.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{Id:              int32(i),Name:            goodsForm.Name,GoodsSn:         goodsForm.GoodsSn,Stocks:          goodsForm.Stocks,MarketPrice:     goodsForm.MarketPrice,ShopPrice:       goodsForm.ShopPrice,GoodsBrief:      goodsForm.GoodsBrief,GoodsDesc:       goodsForm.GoodsDesc,ShipFree:        *goodsForm.ShipFree,Images:          goodsForm.Images,DescImages:      goodsForm.DescImages,GoodsFrontImage: goodsForm.FrontImage,CategoryId:      goodsForm.CategoryId,BrandId:         goodsForm.Brand,}); err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.JSON(http.StatusOK, gin.H{"msg": "修改成功",})}

分类的相关接口

我们在做分类接口之前,意识到有三个接口是大家都共用的,分别是:removeTopStruct、HandleGrpcErrorToHttp、HandleValidatorError ,所以我们可以把这三个接口都抽到base.go 中:

base.go(在 api 包下创建的新接口)

package apiimport ("github.com/gin-gonic/gin""github.com/go-playground/validator/v10""google.golang.org/grpc/codes""google.golang.org/grpc/status""mxshop-api/goods-web/global""net/http""strings"
)func HandleGrpcErrorToHttp(err error, c *gin.Context) {// 将 grpc 的状态码转换为 http 的状态码if err != nil {if e, ok := status.FromError(err); ok {switch e.Code() {case codes.NotFound:c.JSON(http.StatusNotFound, gin.H{"msg": e.Message(),})case codes.Internal:c.JSON(http.StatusInternalServerError, gin.H{"msg": "内部错误",})case codes.InvalidArgument:c.JSON(http.StatusBadRequest, gin.H{"msg": "参数错误",})default:c.JSON(http.StatusInternalServerError, gin.H{"msg": "其他错误:" + e.Message(),})}}}
}// 在最后返回错误时调用,用来将返回中的对象名去掉
func RemoveTopStruct(fields map[string]string) map[string]string {rsp := map[string]string{}for field, err := range fields {rsp[field[strings.Index(field, ".")+1:]] = err // 将map中的 key 中的 . 前面的信息去掉}return rsp
}func HandleValidatorError(c *gin.Context, err error) {errs, ok := err.(validator.ValidationErrors)if !ok {c.JSON(http.StatusOK, gin.H{"msg": err.Error(),})}c.JSON(http.StatusBadRequest, gin.H{"msg": RemoveTopStruct(errs.Translate(global.Trans)),})return
}

创建所需表单

forms/category.go

package formstype CategoryForm struct {Name           string `form:"name" json:"name" binding:"required,min=3,max=20"`ParentCategory int32  `form:"parent" json:"parent"`Level          int32  `form:"level" json:"level" binding:"required,oneof=1 2 3"`IsTab          *bool  `form:"is_tab" json:"is_tab" binding:"required"`
}type UpdateCategoryForm struct {Name  string `form:"name" json:"name" binding:"required,min=3,max=20"`IsTab *bool  `form:"is_tab" json:"is_tab"`
}

创建接口

所有接口:

package categoryimport ("context""encoding/json""github.com/gin-gonic/gin""go.uber.org/zap""google.golang.org/protobuf/types/known/emptypb""mxshop-api/goods-web/api""mxshop-api/goods-web/forms""mxshop-api/goods-web/global""mxshop-api/goods-web/proto""net/http""strconv"
)func List(ctx *gin.Context) {r, err := global.GoodsSrvClient.GetAllCategorysList(context.Background(), &emptypb.Empty{})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}// 创建一个数组data := make([]interface{}, 0)err = json.Unmarshal([]byte(r.JsonData), &data) // 这里是逻辑写成这样了,所有的分级分类会以JSON的形式存储在r.JsonData 中,这里是对应的反解if err != nil {zap.S().Errorw("[List] 查询 【分类列表】 失败", err.Error())}ctx.JSON(http.StatusOK, data)
}func Detail(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}reMap := make(map[string]interface{})subCategorys := make([]interface{}, 0)if r, err := global.GoodsSrvClient.GetSubCategory(context.Background(), &proto.CategoryListRequest{Id: int32(i),}); err != nil {api.HandleGrpcErrorToHttp(err, ctx)return} else {for _, value := range r.SubCategorys {subCategorys = append(subCategorys, map[string]interface{}{"id":              value.Id,"name":            value.Name,"level":           value.Level,"parent_category": value.ParentCategory,"is_tab":          value.IsTab,})}reMap["id"] = r.Info.IdreMap["name"] = r.Info.NamereMap["level"] = r.Info.LevelreMap["parent_category"] = r.Info.ParentCategoryreMap["sub_category"] = subCategorysctx.JSON(http.StatusOK, reMap)}return
}func New(ctx *gin.Context) {categoryForm := forms.CategoryForm{}if err := ctx.ShouldBindJSON(&categoryForm); err != nil {api.HandleValidatorError(ctx, err)return}rsp, err := global.GoodsSrvClient.CreateCategory(context.Background(), &proto.CategoryInfoRequest{Name:           categoryForm.Name,IsTab:          *categoryForm.IsTab,Level:          categoryForm.Level,ParentCategory: categoryForm.ParentCategory,})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)}request := make(map[string]interface{})request["id"] = rsp.Idrequest["name"] = rsp.Namerequest["parent"] = rsp.ParentCategoryrequest["level"] = rsp.Levelrequest["is_tab"] = rsp.IsTabctx.JSON(http.StatusOK, request)
}func Delete(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}//1. 先查询出该分类写的所有子分类//2. 将所有的分类全部逻辑删除//3. 将该分类下的所有的商品逻辑删除_, err = global.GoodsSrvClient.DeleteCategory(context.Background(), &proto.DeleteCategoryRequest{Id: int32(i)})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.Status(http.StatusOK)
}func Update(ctx *gin.Context) {categoryForm := forms.UpdateCategoryForm{}if err := ctx.ShouldBindJSON(&categoryForm); err != nil {api.HandleValidatorError(ctx, err)return}id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}request := &proto.CategoryInfoRequest{Id:   int32(i),Name: categoryForm.Name,}if categoryForm.IsTab != nil {request.IsTab = *categoryForm.IsTab}_, err = global.GoodsSrvClient.UpdateCategory(context.Background(), request)if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.Status(http.StatusOK)
}

添加 router

router/category.go

package routerimport ("github.com/gin-gonic/gin""mxshop-api/goods-web/api/category"
)func InitCategoryRouter(Router *gin.RouterGroup) {CategoryRouter := Router.Group("category"){CategoryRouter.GET("", category.List)CategoryRouter.DELETE("/:id", category.Delete)CategoryRouter.GET("/:id", category.Detail)CategoryRouter.POST("", category.New)CategoryRouter.PUT("/:id", category.Update)}
}

在Init 中添加category

initialize/router.go:

	ApiGroup := Router.Group("/g/v1")router2.InitGoodsRouter(ApiGroup)router2.InitCategoryRouter(ApiGroup) // q添加router2.InitHealthCheckRouter(Router.Group(""))

轮播图接口

添加轮播图Form

创建文件 forms/banner.go

package formstype BannerForm struct {Image string `form:"image" json:"image" binding:"url"`Index int `form:"index" json:"index" binding:"required"`Url string `form:"url" json:"url" binding:"url"`
}

编写API

创建文件 api/banner/banner.go

package bannersimport ("context""github.com/gin-gonic/gin""google.golang.org/protobuf/types/known/emptypb""mxshop-api/goods-web/api""mxshop-api/goods-web/forms""mxshop-api/goods-web/global""mxshop-api/goods-web/proto""net/http""strconv"
)func List(ctx *gin.Context) {rsp, err := global.GoodsSrvClient.BannerList(context.Background(), &emptypb.Empty{})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}result := make([]interface{}, 0)for _, value := range rsp.Data {reMap := make(map[string]interface{})reMap["id"] = value.IdreMap["index"] = value.IndexreMap["image"] = value.ImagereMap["url"] = value.Urlresult = append(result, reMap)}ctx.JSON(http.StatusOK, result)
}func New(ctx *gin.Context) {// 接收新增的信息bannerForm := forms.BannerForm{}if err := ctx.ShouldBindJSON(&bannerForm); err != nil {api.HandleValidatorError(ctx, err)return}rsp, err := global.GoodsSrvClient.CreateBanner(context.Background(), &proto.BannerRequest{Index: int32(bannerForm.Index),Image: bannerForm.Image,Url:   bannerForm.Url,})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}response := make(map[string]interface{})response["id"] = rsp.Idresponse["index"] = rsp.Indexresponse["url"] = rsp.Urlresponse["image"] = rsp.Imagectx.JSON(http.StatusOK, response)
}func Update(ctx *gin.Context) {bannerForm := forms.BannerForm{}if err := ctx.ShouldBindJSON(&bannerForm); err != nil {api.HandleValidatorError(ctx, err)return}id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}_, err = global.GoodsSrvClient.UpdateBanner(context.Background(), &proto.BannerRequest{Id:    int32(i),Index: int32(bannerForm.Index),Url:   bannerForm.Url,})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.Status(http.StatusOK)
}func Delete(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}_, err = global.GoodsSrvClient.DeleteBanner(context.Background(), &proto.BannerRequest{Id: int32(i)})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.JSON(http.StatusOK, "")
}

编写Router

创建文件 router/banner.go

package routerimport ("github.com/gin-gonic/gin""mxshop-api/goods-web/api/banners""mxshop-api/goods-web/middlewares"
)func InitBannerRouter(Router *gin.RouterGroup) {BannerRouter := Router.Group("banner"){BannerRouter.GET("", banners.List)BannerRouter.DELETE("/:id", middlewares.JWTAuth(), middlewares.IsAdminAuth(), banners.Delete)BannerRouter.POST("", middlewares.JWTAuth(), middlewares.IsAdminAuth(), banners.New)BannerRouter.PUT("/:id", middlewares.JWTAuth(), middlewares.IsAdminAuth(), banners.Update)}
}

将Router添加至InitRouter

	ApiGroup := Router.Group("/g/v1")router2.InitGoodsRouter(ApiGroup)router2.InitCategoryRouter(ApiGroup)router2.InitBannerRouter(ApiGroup)router2.InitHealthCheckRouter(Router.Group(""))return Router

品牌接口

添加品牌表单

package formstype BrandForm struct {Name string `form:"name" json:"name" binding:"required,min=3,max=10"`Logo string `form:"logo" json:"logo" binding:"url"`
}type CategoryBrandForm struct {CategoryId int `form:"category_id" json:"category_id" binding:"required"`BrandId    int `form:"brand_id" json:"brand_id" binding:"required"`
}

添加品牌API

注意这里的分页是不好的写法,正确的应该在service层中实现,所以这里不要参考,具体可以参考商品那里的接口

package brandsimport ("context""net/http""strconv""github.com/gin-gonic/gin""mxshop-api/goods-web/api""mxshop-api/goods-web/forms""mxshop-api/goods-web/global""mxshop-api/goods-web/proto"
)func BrandList(ctx *gin.Context) {pn := ctx.DefaultQuery("pn", "0")pnInt, _ := strconv.Atoi(pn)pSize := ctx.DefaultQuery("psize", "10")pSizeInt, _ := strconv.Atoi(pSize)rsp, err := global.GoodsSrvClient.BrandList(context.Background(), &proto.BrandFilterRequest{Pages:       int32(pnInt),PagePerNums: int32(pSizeInt),})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}result := make([]interface{}, 0)reMap := make(map[string]interface{})reMap["total"] = rsp.Totalfor _, value := range rsp.Data[pnInt : pnInt*pSizeInt+pSizeInt] {reMap := make(map[string]interface{})reMap["id"] = value.IdreMap["name"] = value.NamereMap["logo"] = value.Logoresult = append(result, reMap)}reMap["data"] = resultctx.JSON(http.StatusOK, reMap)
}func NewBrand(ctx *gin.Context) {brandForm := forms.BrandForm{}if err := ctx.ShouldBindJSON(&brandForm); err != nil {api.HandleValidatorError(ctx, err)return}rsp, err := global.GoodsSrvClient.CreateBrand(context.Background(), &proto.BrandRequest{Name: brandForm.Name,Logo: brandForm.Logo,})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}request := make(map[string]interface{})request["id"] = rsp.Idrequest["name"] = rsp.Namerequest["logo"] = rsp.Logoctx.JSON(http.StatusOK, request)
}func DeleteBrand(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}_, err = global.GoodsSrvClient.DeleteBrand(context.Background(), &proto.BrandRequest{Id: int32(i)})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.Status(http.StatusOK)
}func UpdateBrand(ctx *gin.Context) {brandForm := forms.BrandForm{}if err := ctx.ShouldBindJSON(&brandForm); err != nil {api.HandleValidatorError(ctx, err)return}id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}_, err = global.GoodsSrvClient.UpdateBrand(context.Background(), &proto.BrandRequest{Id:   int32(i),Name: brandForm.Name,Logo: brandForm.Logo,})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.Status(http.StatusOK)
}func GetCategoryBrandList(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}rsp, err := global.GoodsSrvClient.GetCategoryBrandList(context.Background(), &proto.CategoryInfoRequest{Id: int32(i),})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}result := make([]interface{}, 0)for _, value := range rsp.Data {reMap := make(map[string]interface{})reMap["id"] = value.IdreMap["name"] = value.NamereMap["logo"] = value.Logoresult = append(result, reMap)}ctx.JSON(http.StatusOK, result)
}func CategoryBrandList(ctx *gin.Context) {//所有的list返回的数据结构/*{"total": 100,"data":[{},{}]}*/rsp, err := global.GoodsSrvClient.CategoryBrandList(context.Background(), &proto.CategoryBrandFilterRequest{})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}reMap := map[string]interface{}{"total": rsp.Total,}result := make([]interface{}, 0)for _, value := range rsp.Data {reMap := make(map[string]interface{})reMap["id"] = value.IdreMap["category"] = map[string]interface{}{"id":   value.Category.Id,"name": value.Category.Name,}reMap["brand"] = map[string]interface{}{"id":   value.Brand.Id,"name": value.Brand.Name,"logo": value.Brand.Logo,}result = append(result, reMap)}reMap["data"] = resultctx.JSON(http.StatusOK, reMap)
}func NewCategoryBrand(ctx *gin.Context) {categoryBrandForm := forms.CategoryBrandForm{}if err := ctx.ShouldBindJSON(&categoryBrandForm); err != nil {api.HandleValidatorError(ctx, err)return}rsp, err := global.GoodsSrvClient.CreateCategoryBrand(context.Background(), &proto.CategoryBrandRequest{CategoryId: int32(categoryBrandForm.CategoryId),BrandId:    int32(categoryBrandForm.BrandId),})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}response := make(map[string]interface{})response["id"] = rsp.Idctx.JSON(http.StatusOK, response)
}func UpdateCategoryBrand(ctx *gin.Context) {categoryBrandForm := forms.CategoryBrandForm{}if err := ctx.ShouldBindJSON(&categoryBrandForm); err != nil {api.HandleValidatorError(ctx, err)return}id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}_, err = global.GoodsSrvClient.UpdateCategoryBrand(context.Background(), &proto.CategoryBrandRequest{Id:         int32(i),CategoryId: int32(categoryBrandForm.CategoryId),BrandId:    int32(categoryBrandForm.BrandId),})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.Status(http.StatusOK)
}func DeleteCategoryBrand(ctx *gin.Context) {id := ctx.Param("id")i, err := strconv.ParseInt(id, 10, 32)if err != nil {ctx.Status(http.StatusNotFound)return}_, err = global.GoodsSrvClient.DeleteCategoryBrand(context.Background(), &proto.CategoryBrandRequest{Id: int32(i)})if err != nil {api.HandleGrpcErrorToHttp(err, ctx)return}ctx.JSON(http.StatusOK, "")
}

添加品牌Router

package routerimport ("github.com/gin-gonic/gin""mxshop-api/goods-web/api/brands"
)// 1. 商品的api接口开发完成
// 2. 图片的坑
func InitBrandRouter(Router *gin.RouterGroup) {BrandRouter := Router.Group("brands"){BrandRouter.GET("", brands.BrandList)          // 品牌列表页BrandRouter.DELETE("/:id", brands.DeleteBrand) // 删除品牌BrandRouter.POST("", brands.NewBrand)          //新建品牌BrandRouter.PUT("/:id", brands.UpdateBrand)    //修改品牌信息}CategoryBrandRouter := Router.Group("categorybrands"){CategoryBrandRouter.GET("", brands.CategoryBrandList)          // 类别品牌列表页CategoryBrandRouter.DELETE("/:id", brands.DeleteCategoryBrand) // 删除类别品牌CategoryBrandRouter.POST("", brands.NewCategoryBrand)          //新建类别品牌CategoryBrandRouter.PUT("/:id", brands.UpdateCategoryBrand)    //修改类别品牌CategoryBrandRouter.GET("/:id", brands.GetCategoryBrandList)   //获取分类的品牌}
}

品牌路由导入路由表

	ApiGroup := Router.Group("/g/v1")router2.InitGoodsRouter(ApiGroup)router2.InitCategoryRouter(ApiGroup)router2.InitBannerRouter(ApiGroup)router2.InitBrandRouter(ApiGroup)router2.InitHealthCheckRouter(Router.Group(""))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/70795.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WiseFlow本地搭建实录---保姆教程

今天从零开始搭建了Wiseflow的本地环境搭建&#xff0c;目前使用的都是免费的API&#xff0c;我建议大家可以一起尝试一下搭建自己的关键信息的数据库&#xff0c;我是windows的环境&#xff0c;但是其他的应该也差不多&#xff0c;踩了很多坑&#xff0c;希望这篇文章能帮大家…

数的计算(蓝桥云课)

题目描述 输入一个自然数 n (n≤1000)n (n≤1000)&#xff0c;我们对此自然数按照如下方法进行处理: 不作任何处理; 在它的左边加上一个自然数,但该自然数不能超过原数的一半; 加上数后,继续按此规则进行处理,直到不能再加自然数为止。 问总共可以产生多少个数。 输入描述 输…

知识库功能测试难点

图表交互功能测试难点 知识库图表类型多&#xff0c;每种图表交互功能不同。像柱状图&#xff0c;可能有点击柱子查看详细数据、鼠标悬停显示数据提示等交互&#xff1b;折线图除了这些&#xff0c;还可能支持缩放查看不同时间段数据。多种交互操作在不同图表间存在差异&#x…

【人工智能】数据挖掘与应用题库(201-300)

1、在LetNet5网络中,卷积核的大小是? 答案:5*5 2、LeNet5网络参数的数量约为? 答案:6万 3、AlexNet与LeNet5相比,使用了哪些机制来改进模型的训练过程? 答案: 数据增广Dropout抑制过拟合ReLU激活函数CUDA加速神经网络训练4、VGGNet使用的卷积核的大小是? 答案:…

web安全渗透测试 APP安全渗透漏洞测试详情

前言 小小白承包了一块20亩的土地&#xff0c;依山傍水&#xff0c;风水不错。听朋友说去年玉米大卖&#xff0c;他也想尝尝甜头&#xff0c;也就种上了玉米。 看着玉米茁壮成长&#xff0c;别提小小白心里多开心&#xff0c;心里盘算着玉米大买后&#xff0c;吃香喝辣的富贵…

CSS处理内容溢出

<!DOCTYPE html> <html lang"zh-cn"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>处理内容溢出</title><style>#d1{wid…

拉丁超立方采样(Latin Hypercube Sampling)技术详解及实现

拉丁超立方采样(Latin Hypercube Sampling)技术详解 拉丁超立方采样(Latin Hypercube Sampling)技术详解1. 引言2. 拉丁超立方采样原理3. 数学公式描述4. Python代码实现代码解析5. 应用场景与优势6. 在化工中的应用6.1 工艺参数优化6.2 不确定性量化与风险评估6.3 实验设计…

docker-compose部署onlyoffice8.3.0并支持ssl,且支持通过nginx代理,关闭JWT配置

编写docker-compose文件 mkdir -p /data/onlyoffice && echo "version: 3services:onlyoffice:container_name: OnlyOfficeimage: onlyoffice/documentserver:8.3.0restart: alwaysports:- 8088:80- 64431:443environment:TZ: Asia/ShanghaiJWT_ENABLED: falsevol…

Sliding Window Attention(滑动窗口注意力)解析: Pytorch实现并结合全局注意力(Global Attention )

Sliding Window Attention&#xff08;滑动窗口注意力&#xff09;解析 Sliding Window Attention&#xff08;滑动窗口注意力&#xff09; 是 Longformer (来源&#xff1a;https://arxiv.org/pdf/2004.05150)提出的 稀疏注意力机制&#xff0c;旨在解决 标准 Transformer 计算…

【运维】内网服务器借助通过某台可上外网的服务器实现公网访问

背景&#xff1a; 内网服务器无法连接公网,但是办公电脑可以连接内网服务器又可以连接公网。 安装软件 1、frp 2、ccproxy 配置 1、内网服务器 # 内网服务器启动frp服务配置文件参考vi frps.ini# frps.ini [common] bind_port 7000# 备注: bind_port端口可以随意配置。配置完…

flask 是如何分发请求的?

这篇博客会涉及一些 WSGI 的知识&#xff0c;不了解的可以看这篇博客&#xff0c;简单了解一下。 Python 的 WSGI 简单入门 一、请求在 flask 中的处理过程 我们先来看一下 werkzeug.routing 包下 Map 和 Rule 方法的使用&#xff0c;这里给出一个官方的示例&#xff08;我进…

怎么获取免费的 GPU 资源完成大语言模型(LLM)实验

怎么获取免费的 GPU 资源完成大语言模型(LLM)实验 目录 怎么获取免费的 GPU 资源完成大语言模型(LLM)实验在线平台类Google ColabKaggle NotebooksHugging Face Spaces百度飞桨 AI Studio在线平台类 Google Colab 特点:由 Google 提供的基于云端的 Jupyter 笔记本环境,提…

Python开发Django面试题及参考答案

目录 Django 的请求生命周期是怎样的? Django 的 MTV 架构中的各个组件分别是什么? Django 的 URL 路由是如何工作的? Django 的视图函数和视图类有什么区别? Django 的模板系统是如何渲染 HTML 的? Django 的 ORM 是如何工作的? Django 的中间件是什么?它的作用是…

【图像的读写与基本操作】

图像的读写与基本操作 目录 图像的读写与基本操作目标知识点1. 图像的读写 &#xff1a;2. 图像的缩放 &#xff1a;3. 图像的翻转 &#xff1a;4. 图像的裁剪 &#xff1a;5. 颜色空间转换 &#xff1a; 示例代码1. 图像的读写 &#xff1a;2. 图像的缩放 &#xff1a;3. 图像…

《数字图像处理》笔记

文章目录 第一章 绪论1.1 什么是数字图像处理数字图像的概念数字图像的组成数字图像处理的概念 1.4 数字图像处理的基本步骤 第二章 数字图像基础2.2 光和电磁波谱可见光单色光灰度级发光强度光通量亮度 2.3 图像感知和获取将照射能量变换为数字图像的传感器简单的图像形成模型…

网络安全扫描--基础篇

前言 1、了解互联网安全领域中日趋重要的扫描技术 2、了解在不同网络场景下扫描技术手段 3、熟悉linux下系统内核防护策略并能大件一个有效的系统防护体系 4、增强工作安全意识&#xff0c;并能有效的实践于工作场景中 目录 1、熟悉主机扫描工具&#xff08;fping&#xff0c;…

前端防重复请求终极方案:从Loading地狱到精准拦截的架构升级

&#x1f525; 事故现场还原&#xff1a;疯狂点击引发的血案 凌晨1点23分&#xff0c;监控系统突然告警&#xff1a; &#x1f4c9; 服务器CPU飙升至98% &#x1f5c3;️ 数据库出现3000脏数据 &#x1f4a5; 用户端弹出上百个错误弹窗 事故原因&#xff1a;黑产脚本通过0.5秒…

基于Spring Boot的供应商管理系统设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

Redis|事务

文章目录 是什么能干嘛Redis 事务 VS 数据库事务怎么玩小总结 是什么 首先回想一下什么是数据库的事务&#xff1f;数据库事务是指作为单个逻辑单元执行的一系列操作&#xff0c;具备以下四个关键特性&#xff08;ACID&#xff09;&#xff1a; 原子性&#xff08;Atomicity&am…

一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用

锋哥原创的Flask3 Python Web开发 Flask3视频教程&#xff1a; 2025版 Flask3 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili 不管是开发网站还是后台管理系统&#xff0c;我们页面里多多少少有公共的模块。比如博客网站&#xff0c;就有公共的头部&…