1. form

  1. package forms
  2. type BrandForm struct {
  3. Name string `form:"name" json:"name" binding:"required,min=3,max=10"`
  4. Logo string `form:"logo" json:"logo" binding:"url"`
  5. }
  6. type CategoryBrandForm struct {
  7. CategoryId int `form:"category_id" json:"category_id" binding:"required"`
  8. BrandId int `form:"brand_id" json:"brand_id" binding:"required"`
  9. }

2. handler

  1. package brands
  2. import (
  3. "context"
  4. "github.com/gin-gonic/gin"
  5. "github.com/go-playground/validator/v10"
  6. "github.com/golang/protobuf/ptypes/empty"
  7. "google.golang.org/grpc/codes"
  8. "google.golang.org/grpc/status"
  9. "mxshop-api/goods-web/forms"
  10. "mxshop-api/goods-web/global"
  11. "mxshop-api/goods-web/proto"
  12. "net/http"
  13. "strconv"
  14. "strings"
  15. )
  16. func removeTopStruct(fields map[string]string) map[string]string{
  17. rsp := map[string]string{}
  18. for field, err := range fields {
  19. rsp[field[strings.Index(field, ".")+1:]] = err
  20. }
  21. return rsp
  22. }
  23. func HandleGrpcErrorToHttp(err error, c *gin.Context) {
  24. //将grpc的code转换成http的状态码
  25. if err != nil {
  26. if e, ok := status.FromError(err); ok {
  27. switch e.Code() {
  28. case codes.NotFound:
  29. c.JSON(http.StatusNotFound, gin.H{
  30. "msg": e.Message(),
  31. })
  32. case codes.Internal:
  33. c.JSON(http.StatusInternalServerError, gin.H{
  34. "msg:": "内部错误",
  35. })
  36. case codes.InvalidArgument:
  37. c.JSON(http.StatusBadRequest, gin.H{
  38. "msg": "参数错误",
  39. })
  40. case codes.Unavailable:
  41. c.JSON(http.StatusInternalServerError, gin.H{
  42. "msg": "用户服务不可用",
  43. })
  44. default:
  45. c.JSON(http.StatusInternalServerError, gin.H{
  46. "msg": e.Code(),
  47. })
  48. }
  49. return
  50. }
  51. }
  52. }
  53. func HandleValidatorError(c *gin.Context, err error){
  54. errs, ok := err.(validator.ValidationErrors)
  55. if !ok {
  56. c.JSON(http.StatusOK, gin.H{
  57. "msg":err.Error(),
  58. })
  59. }
  60. c.JSON(http.StatusBadRequest, gin.H{
  61. "error": removeTopStruct(errs.Translate(global.Trans)),
  62. })
  63. return
  64. }
  65. func BrandList(ctx *gin.Context) {
  66. pn := ctx.DefaultQuery("pn", "0")
  67. pnInt, _ := strconv.Atoi(pn)
  68. pSize := ctx.DefaultQuery("psize", "10")
  69. pSizeInt, _ := strconv.Atoi(pSize)
  70. rsp, err := global.GoodsSrvClient.BrandList(context.Background(), &proto.BrandFilterRequest{
  71. Pages: int32(pnInt),
  72. PagePerNums: int32(pSizeInt),
  73. })
  74. if err != nil {
  75. api.HandleGrpcErrorToHttp(err, ctx)
  76. return
  77. }
  78. result := make([]interface{}, 0)
  79. reMap := make(map[string]interface{})
  80. reMap["total"] = rsp.Total
  81. for _, value := range rsp.Data[pnInt:pnInt*pSizeInt+pSizeInt] {
  82. reMap := make(map[string]interface{})
  83. reMap["id"] = value.Id
  84. reMap["name"] = value.Name
  85. reMap["logo"] = value.Logo
  86. result = append(result, reMap)
  87. }
  88. reMap["data"] = result
  89. ctx.JSON(http.StatusOK, reMap)
  90. }
  91. func NewBrand(ctx *gin.Context) {
  92. brandForm := forms.BrandForm{}
  93. if err := ctx.ShouldBindJSON(&brandForm); err != nil {
  94. HandleValidatorError(ctx, err)
  95. return
  96. }
  97. rsp, err := global.GoodsSrvClient.CreateBrand(context.Background(), &proto.BrandRequest{
  98. Name: brandForm.Name,
  99. Logo: brandForm.Logo,
  100. })
  101. if err != nil {
  102. HandleGrpcErrorToHttp(err, ctx)
  103. return
  104. }
  105. request := make(map[string]interface{})
  106. request["id"] = rsp.Id
  107. request["name"] = rsp.Name
  108. request["logo"] = rsp.Logo
  109. ctx.JSON(http.StatusOK, request)
  110. }
  111. func DeleteBrand(ctx *gin.Context) {
  112. id := ctx.Param("id")
  113. i, err := strconv.ParseInt(id, 10, 32)
  114. if err != nil {
  115. ctx.Status(http.StatusNotFound)
  116. return
  117. }
  118. _, err = global.GoodsSrvClient.DeleteBrand(context.Background(), &proto.BrandRequest{Id: int32(i)})
  119. if err != nil {
  120. HandleGrpcErrorToHttp(err, ctx)
  121. return
  122. }
  123. ctx.Status(http.StatusOK)
  124. }
  125. func UpdateBrand(ctx *gin.Context) {
  126. brandForm := forms.BrandForm{}
  127. if err := ctx.ShouldBindJSON(&brandForm); err != nil {
  128. HandleValidatorError(ctx, err)
  129. return
  130. }
  131. id := ctx.Param("id")
  132. i, err := strconv.ParseInt(id, 10, 32)
  133. if err != nil {
  134. ctx.Status(http.StatusNotFound)
  135. return
  136. }
  137. _, err = global.GoodsSrvClient.UpdateBrand(context.Background(), &proto.BrandRequest{
  138. Id: int32(i),
  139. Name: brandForm.Name,
  140. Logo: brandForm.Logo,
  141. })
  142. if err != nil {
  143. HandleGrpcErrorToHttp(err, ctx)
  144. return
  145. }
  146. ctx.Status(http.StatusOK)
  147. }
  148. func GetCategoryBrand(ctx *gin.Context) {
  149. id := ctx.Param("id")
  150. i, err := strconv.ParseInt(id, 10, 32)
  151. if err != nil {
  152. ctx.Status(http.StatusNotFound)
  153. return
  154. }
  155. rsp, err := global.GoodsSrvClient.GetCategoryBrandList(context.Background(), &proto.CategoryInfoRequest{
  156. Id: int32(i),
  157. })
  158. if err != nil {
  159. HandleGrpcErrorToHttp(err, ctx)
  160. return
  161. }
  162. ctx.JSON(http.StatusOK, rsp.Data)
  163. }
  164. func GetCategoryBrandList(ctx *gin.Context) {
  165. id := ctx.Param("id")
  166. i, err := strconv.ParseInt(id, 10, 32)
  167. if err != nil {
  168. ctx.Status(http.StatusNotFound)
  169. return
  170. }
  171. rsp, err := global.GoodsSrvClient.GetCategoryBrandList(context.Background(), &proto.CategoryInfoRequest{
  172. Id:int32(i),
  173. })
  174. if err != nil {
  175. HandleGrpcErrorToHttp(err, ctx)
  176. return
  177. }
  178. result := make([]interface{}, 0)
  179. for _, value := range rsp.Data {
  180. reMap := make(map[string]interface{})
  181. reMap["id"] = value.Id
  182. reMap["name"] = value.Name
  183. reMap["logo"] = value.Logo
  184. result = append(result, reMap)
  185. }
  186. ctx.JSON(http.StatusOK, result)
  187. }
  188. func CategoryBrandList(ctx *gin.Context) {
  189. rsp, err := global.GoodsSrvClient.CategoryBrandList(context.Background(), &proto.CategoryBrandFilterRequest{})
  190. if err != nil {
  191. HandleGrpcErrorToHttp(err, ctx)
  192. return
  193. }
  194. reMap := map[string]interface{}{
  195. "total": rsp.Total,
  196. }
  197. result := make([]interface{}, 0)
  198. for _, value := range rsp.Data {
  199. reMap := make(map[string]interface{})
  200. reMap["id"] = value.Id
  201. reMap["category"] = map[string]interface{}{
  202. "id": value.Category.Id,
  203. "name": value.Category.Name,
  204. }
  205. reMap["brand"] = map[string]interface{}{
  206. "id": value.Brand.Id,
  207. "name": value.Brand.Name,
  208. "logo": value.Brand.Logo,
  209. }
  210. result = append(result, reMap)
  211. }
  212. reMap["data"] = result
  213. ctx.JSON(http.StatusOK, reMap)
  214. }
  215. func NewCategoryBrand(ctx *gin.Context) {
  216. categoryBrandForm := forms.CategoryBrandForm{}
  217. if err := ctx.ShouldBindJSON(&categoryBrandForm); err != nil {
  218. HandleValidatorError(ctx, err)
  219. return
  220. }
  221. rsp, err := global.GoodsSrvClient.CreateCategoryBrand(context.Background(), &proto.CategoryBrandRequest{
  222. CategoryId: int32(categoryBrandForm.CategoryId),
  223. BrandId: int32(categoryBrandForm.BrandId),
  224. })
  225. if err != nil {
  226. HandleGrpcErrorToHttp(err, ctx)
  227. return
  228. }
  229. response := make(map[string]interface{})
  230. response["id"] = rsp.Id
  231. ctx.JSON(http.StatusOK, response)
  232. }
  233. func UpdateCategoryBrand(ctx *gin.Context) {
  234. categoryBrandForm := forms.CategoryBrandForm{}
  235. if err := ctx.ShouldBindJSON(&categoryBrandForm); err != nil {
  236. HandleValidatorError(ctx, err)
  237. return
  238. }
  239. id := ctx.Param("id")
  240. i, err := strconv.ParseInt(id, 10, 32)
  241. if err != nil {
  242. ctx.Status(http.StatusNotFound)
  243. return
  244. }
  245. _, err = global.GoodsSrvClient.UpdateCategoryBrand(context.Background(), &proto.CategoryBrandRequest{
  246. Id: int32(i),
  247. CategoryId: int32(categoryBrandForm.CategoryId),
  248. BrandId: int32(categoryBrandForm.BrandId),
  249. })
  250. if err != nil {
  251. HandleGrpcErrorToHttp(err, ctx)
  252. return
  253. }
  254. ctx.Status(http.StatusOK)
  255. }
  256. func DeleteCategoryBrand(ctx *gin.Context) {
  257. id := ctx.Param("id")
  258. i, err := strconv.ParseInt(id, 10, 32)
  259. if err != nil {
  260. ctx.Status(http.StatusNotFound)
  261. return
  262. }
  263. _, err = global.GoodsSrvClient.DeleteCategoryBrand(context.Background(), &proto.CategoryBrandRequest{Id: int32(i)})
  264. if err != nil {
  265. HandleGrpcErrorToHttp(err, ctx)
  266. return
  267. }
  268. ctx.JSON(http.StatusOK, "")
  269. }

3. router

  1. package router
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "mxshop-api/goods-web/api/brands"
  5. )
  6. func InitBrandRouter(Router *gin.RouterGroup) {
  7. BrandRouter := Router.Group("brands")
  8. {
  9. BrandRouter.GET("", brands.BrandList) // 品牌列表页
  10. BrandRouter.DELETE("/:id", brands.DeleteBrand) // 删除品牌
  11. BrandRouter.POST("", brands.NewBrand) //新建品牌
  12. BrandRouter.PUT("/:id", brands.UpdateBrand) //修改品牌信息
  13. }
  14. CategoryBrandRouter := Router.Group("categorybrands")
  15. {
  16. CategoryBrandRouter.GET("", brands.CategoryBrandList) // 类别品牌列表页
  17. CategoryBrandRouter.DELETE("/:id", brands.DeleteCategoryBrand) // 删除类别品牌
  18. CategoryBrandRouter.POST("", brands.NewCategoryBrand) //新建类别品牌
  19. CategoryBrandRouter.PUT("/:id", brands.UpdateCategoryBrand) //修改类别品牌
  20. CategoryBrandRouter.GET("/:id", brands.GetCategoryBrandList) //获取分类的品牌
  21. }
  22. }

4. 在初始化配置router