1. form
package forms
type 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"`
}
2. handler
package banners
import (
"context"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/golang/protobuf/ptypes/empty"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"mxshop-api/goods-web/forms"
"mxshop-api/goods-web/global"
"mxshop-api/goods-web/proto"
"net/http"
"strconv"
"strings"
)
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
}
return rsp
}
func HandleGrpcErrorToHttp(err error, c *gin.Context) {
//将grpc的code转换成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": "参数错误",
})
case codes.Unavailable:
c.JSON(http.StatusInternalServerError, gin.H{
"msg": "用户服务不可用",
})
default:
c.JSON(http.StatusInternalServerError, gin.H{
"msg": e.Code(),
})
}
return
}
}
}
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{
"error": removeTopStruct(errs.Translate(global.Trans)),
})
return
}
func BannerList(ctx *gin.Context) {
rsp, err := global.GoodsSrvClient.BannerList(context.Background(), &empty.Empty{})
if err != nil {
HandleGrpcErrorToHttp(err, ctx)
return
}
result := make([]interface{}, 0)
for _, value := range rsp.Data {
reMap := make(map[string]interface{})
reMap["id"] = value.Id
reMap["index"] = value.Index
reMap["image"] = value.Image
reMap["url"] = value.Url
result = append(result, reMap)
}
ctx.JSON(http.StatusOK, result)
}
func NewBanner(ctx *gin.Context) {
bannerForm := forms.BannerForm{}
if err := ctx.ShouldBindJSON(&bannerForm); err != nil {
HandleValidatorError(ctx, err)
return
}
rsp, err := global.GoodsSrvClient.CreateBanner(context.Background(), &proto.BannerRequest{
Index: int32(bannerForm.Index),
Url: bannerForm.Url,
Image: bannerForm.Image,
})
if err != nil {
HandleGrpcErrorToHttp(err, ctx)
return
}
response := make(map[string]interface{})
response["id"] = rsp.Id
response["index"] = rsp.Index
response["url"] = rsp.Url
response["image"] = rsp.Image
ctx.JSON(http.StatusOK, response)
}
func UpdateBanner(ctx *gin.Context) {
bannerForm := forms.BannerForm{}
if err := ctx.ShouldBindJSON(&bannerForm); err != nil {
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 {
HandleGrpcErrorToHttp(err, ctx)
return
}
ctx.Status(http.StatusOK)
}
func DeleteBanner(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 {
HandleGrpcErrorToHttp(err, ctx)
return
}
ctx.JSON(http.StatusOK, "")
}
3. router
package router
import (
"github.com/gin-gonic/gin"
"mxshop-api/goods-web/api/banners"
"mxshop-api/goods-web/middlewares"
)
func InitBannerRouter(Router *gin.RouterGroup) {
BannerRouter := Router.Group("banners")
{
BannerRouter.GET("", banners.BannerList) // 轮播图列表页
BannerRouter.DELETE("/:id", middlewares.JWTAuth(), middlewares.IsAdminAuth(), banners.DeleteBanner) // 删除轮播图
BannerRouter.POST("", middlewares.JWTAuth(), middlewares.IsAdminAuth(), banners.NewBanner) //新建轮播图
BannerRouter.PUT("/:id", middlewares.JWTAuth(), middlewares.IsAdminAuth(), banners.UpdateBanner) //修改轮播图信息
}
}
3. 在初始化中调用router