├── .gitignore ├── README.md ├── api └── v1 │ ├── enter.go │ ├── mall │ ├── enter.go │ ├── mall_goods_category.go │ ├── mall_goods_info.go │ ├── mall_index.go │ ├── mall_order.go │ ├── mall_shop_cart.go │ ├── mall_user.go │ └── mall_user_address.go │ └── manage │ ├── enter.go │ ├── manage_admin_user.go │ ├── manage_carousel.go │ ├── manage_goods_category.go │ ├── manage_goods_info.go │ ├── manage_index_config.go │ └── manage_order.go ├── config.yaml ├── config ├── config.go ├── mysql.go ├── oss.go ├── system.go └── zap.go ├── core ├── server.go ├── server_other.go ├── server_win.go ├── viper.go └── zap.go ├── global └── global.go ├── go.mod ├── go.sum ├── initialize ├── gorm.go ├── gorm_mysql.go ├── internal │ ├── gorm.go │ └── logger.go └── router.go ├── main.go ├── middleware ├── cors.go ├── jwt.go └── loadtls.go ├── model ├── common │ ├── enum │ │ ├── goods_category_enum.go │ │ ├── index_config_enum.go │ │ └── mall_order_status.go │ ├── json_time.go │ ├── request │ │ └── common.go │ └── response │ │ ├── common.go │ │ └── response.go ├── example │ ├── exa_breakpoint_continue.go │ ├── exa_file_upload_download.go │ └── response │ │ ├── exa_breakpoint_continue.go │ │ └── exa_file_upload_download.go ├── mall │ ├── mall_order_address.go │ ├── mall_shop_cart_item.go │ ├── mall_user.go │ ├── mall_user_address.go │ ├── mall_user_token.go │ ├── request │ │ ├── mall_goods_info.go │ │ ├── mall_order.go │ │ ├── mall_shop_cart.go │ │ ├── mall_user.go │ │ └── mall_user_address.go │ └── response │ │ ├── mall_carousel.go │ │ ├── mall_goods_category.go │ │ ├── mall_goods_info.go │ │ ├── mall_index_config.go │ │ ├── mall_order.go │ │ ├── mall_shop_cart.go │ │ └── mall_user.go └── manage │ ├── manage_admin_user.go │ ├── manage_admin_user_token.go │ ├── manage_carousel.go │ ├── manage_goods_category.go │ ├── manage_goods_info.go │ ├── manage_index_config.go │ ├── manage_order.go │ ├── manage_order_item.go │ ├── manage_user.go │ ├── request │ ├── manage_admin_user.go │ ├── manage_carousel.go │ ├── manage_goods_category.go │ ├── manage_goods_info.go │ ├── manage_index_config.go │ ├── manage_order.go │ └── manage_user.go │ └── response │ ├── manage_goods_category.go │ └── manage_order.go ├── router ├── enter.go ├── mall │ ├── enter.go │ ├── mall_carousel.go │ ├── mall_goods_category.go │ ├── mall_goods_info.go │ ├── mall_order.go │ ├── mall_shop_cart.go │ ├── mall_user.go │ └── mall_user_address.go └── manage │ ├── enter.go │ ├── manage_admin_user.go │ ├── manage_carousel.go │ ├── manage_goods_category.go │ ├── manage_goods_info.go │ ├── manage_index_config.go │ └── manage_order.go ├── service ├── enter.go ├── example │ ├── enter.go │ ├── exa_breakpoint_continue.go │ └── exa_file_upload_download.go ├── mall │ ├── enter.go │ ├── mall_carousel.go │ ├── mall_goods_category.go │ ├── mall_goods_info.go │ ├── mall_index_info.go │ ├── mall_order.go │ ├── mall_shop_cart.go │ ├── mall_user.go │ ├── mall_user_address.go │ └── mall_user_token.go └── manage │ ├── enter.go │ ├── manage_admin_user.go │ ├── manage_admin_user_token.go │ ├── manage_carousel.go │ ├── manage_goods_category.go │ ├── manage_goods_info.go │ ├── manage_index_config.go │ ├── manage_order.go │ └── manage_user.go ├── static-files ├── newbee-mall.png ├── newbee_mall_db_v2_schema.sql ├── 商品搜索.png ├── 地址管理.png ├── 生成订单.png ├── 登录.png ├── 订单列表.png ├── 订单详情.png ├── 详情页.png ├── 购物车.png ├── 项目结构说明.md └── 首页.png └── utils ├── constant.go ├── directory.go ├── md5.go ├── nums_utils.go ├── rotatelogs.go ├── str_utils.go ├── upload ├── local.go └── upload.go ├── validator.go └── verify.go /.gitignore: -------------------------------------------------------------------------------- 1 | /log/ 2 | log 3 | .idea 4 | static -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](static-files/newbee-mall.png) 2 | 3 | ## 代码已迁移至[newbee-mall仓库](https://github.com/newbee-ltd/newbee-mall-api-go),本地址后续不维护 4 | ### newbee-mall商城go版本 5 | 6 | 本项目为[新蜂商城后端接口 newbee-mall-api](https://github.com/newbee-ltd/newbee-mall-api) 的go版本,使用原版本的所有数据结构 7 | 技术栈为 Gin,主要面向服务端开发人员,前端 Vue 页面源码在另外三个 Vue 仓库。 8 | 前端项目: 9 | - [新蜂商城 Vue2 版本 newbee-mall-vue-app](https://github.com/newbee-ltd/newbee-mall-vue-app) 10 | - [新蜂商城 Vue3 版本 newbee-mall-vue3-app](https://github.com/newbee-ltd/newbee-mall-vue3-app) 11 | - [新蜂商城后台管理系统 Vue3 版本 vue3-admin](https://github.com/newbee-ltd/vue3-admin) 12 | 13 | **如果觉得项目还不错的话可以给项目一个 Star 吧,** 14 | ## 联系作者 15 | 16 | > 大家有任何问题或者建议都可以在 [issues](https://github.com/627886474/newbee-mall-api-go/issues) 中反馈给我 17 | 18 | ### 项目讲解 19 | -- -- 20 | - [【go商城】gin+gorm实现CRUD](https://blog.csdn.net/zxc19854/article/details/125267635) 21 | 22 | ### 本地启动 23 | -- -- 24 | #### 后端项目启动 25 | 首先执行static-files 中的sql文件 26 | 27 | ```bash 28 | # 克隆项目 29 | git clone https://github.com/627886474/newbee-mall-api-go 30 | 31 | # 使用 go mod 并安装go依赖包 32 | go generate 33 | # 编译 34 | go build -o server main.go (windows编译命令为go build -o server.exe main.go ) 35 | # 运行二进制 36 | ./server (windows运行命令为 server.exe) 37 | ``` 38 | #### 前端项目启动 39 | 40 | 然后按照原项目的部署说明部署即可 41 | 42 | [后台管理项目](https://github.com/newbee-ltd/vue3-admin) 43 | 44 | 测试用户名:admin 测试密码:123456 45 | 46 | 47 | [前台商城](https://github.com/newbee-ltd/newbee-mall-vue3-app) 48 | 49 | 直接注册账号就可以了 50 | -- -- 51 | 52 | 53 | ## 页面展示 54 | 55 | 以下为新蜂商城 Vue 版本的页面预览: 56 | 57 | - 登录页 58 | 59 | ![](static-files/登录.png) 60 | 61 | - 首页 62 | 63 | ![](static-files/首页.png) 64 | 65 | - 商品搜索 66 | 67 | ![](static-files/商品搜索.png) 68 | 69 | - 商品详情页 70 | 71 | ![](static-files/详情页.png) 72 | 73 | - 购物车 74 | 75 | ![](static-files/购物车.png) 76 | 77 | - 生成订单 78 | 79 | ![](static-files/生成订单.png) 80 | 81 | - 地址管理 82 | 83 | ![](static-files/地址管理.png) 84 | 85 | - 订单列表 86 | 87 | ![](static-files/订单列表.png) 88 | 89 | - 订单详情 90 | 91 | ![](static-files/订单详情.png) 92 | 93 | ## 感谢 94 | - [newbee-ltd](https://github.com/newbee-ltd) 95 | 96 | - [gin-vue-admin](https://github.com/flipped-aurora/gin-vue-admin) 97 | -------------------------------------------------------------------------------- /api/v1/enter.go: -------------------------------------------------------------------------------- 1 | package v1 2 | 3 | import ( 4 | "main.go/api/v1/mall" 5 | "main.go/api/v1/manage" 6 | ) 7 | 8 | type ApiGroup struct { 9 | ManageApiGroup manage.ManageGroup 10 | MallApiGroup mall.MallGroup 11 | } 12 | 13 | var ApiGroupApp = new(ApiGroup) 14 | -------------------------------------------------------------------------------- /api/v1/mall/enter.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import "main.go/service" 4 | 5 | type MallGroup struct { 6 | MallIndexApi 7 | MallGoodsInfoApi 8 | MallGoodsCategoryApi 9 | MallUserApi 10 | MallUserAddressApi 11 | MallShopCartApi 12 | MallOrderApi 13 | } 14 | 15 | var mallCarouselService = service.ServiceGroupApp.MallServiceGroup.MallCarouselService 16 | var mallGoodsInfoService = service.ServiceGroupApp.MallServiceGroup.MallGoodsInfoService 17 | var mallIndexConfigService = service.ServiceGroupApp.MallServiceGroup.MallIndexInfoService 18 | var mallGoodsCategoryService = service.ServiceGroupApp.MallServiceGroup.MallGoodsCategoryService 19 | var mallUserService = service.ServiceGroupApp.MallServiceGroup.MallUserService 20 | var mallUserTokenService = service.ServiceGroupApp.MallServiceGroup.MallUserTokenService 21 | var mallUserAddressService = service.ServiceGroupApp.MallServiceGroup.MallUserAddressService 22 | var mallShopCartService = service.ServiceGroupApp.MallServiceGroup.MallShopCartService 23 | var mallOrderService = service.ServiceGroupApp.MallServiceGroup.MallOrderService 24 | -------------------------------------------------------------------------------- /api/v1/mall/mall_goods_category.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/response" 8 | ) 9 | 10 | type MallGoodsCategoryApi struct { 11 | } 12 | 13 | //返回分类数据(首页调用) 14 | func (m *MallGoodsCategoryApi) GetGoodsCategory(c *gin.Context) { 15 | err, list := mallGoodsCategoryService.GetCategoriesForIndex() 16 | if err != nil { 17 | global.GVA_LOG.Error("查询失败!", zap.Error(err)) 18 | response.FailWithMessage("查询失败"+err.Error(), c) 19 | } 20 | response.OkWithData(list, c) 21 | } 22 | -------------------------------------------------------------------------------- /api/v1/mall/mall_goods_info.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/response" 8 | "strconv" 9 | ) 10 | 11 | type MallGoodsInfoApi struct { 12 | } 13 | 14 | func (m *MallGoodsInfoApi) GoodsSearch(c *gin.Context) { 15 | 16 | pageNumber, _ := strconv.Atoi(c.Query("pageNumber")) 17 | goodsCategoryId, _ := strconv.Atoi(c.Query("goodsCategoryId")) 18 | keyword := c.Query("keyword") 19 | orderBy := c.Query("orderBy") 20 | 21 | if err, list, total := mallGoodsInfoService.MallGoodsListBySearch(pageNumber, goodsCategoryId, keyword, orderBy); err != nil { 22 | global.GVA_LOG.Error("查询失败!", zap.Error(err)) 23 | response.FailWithMessage("查询失败"+err.Error(), c) 24 | } else { 25 | response.OkWithDetailed(response.PageResult{ 26 | List: list, 27 | TotalCount: total, 28 | CurrPage: pageNumber, 29 | PageSize: 10, 30 | }, "获取成功", c) 31 | } 32 | 33 | } 34 | 35 | func (m *MallGoodsInfoApi) GoodsDetail(c *gin.Context) { 36 | id, _ := strconv.Atoi(c.Param("id")) 37 | err, goodsInfo := mallGoodsInfoService.GetMallGoodsInfo(id) 38 | if err != nil { 39 | global.GVA_LOG.Error("查询失败!", zap.Error(err)) 40 | response.FailWithMessage("查询失败"+err.Error(), c) 41 | } 42 | response.OkWithData(goodsInfo, c) 43 | } 44 | -------------------------------------------------------------------------------- /api/v1/mall/mall_index.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/enum" 8 | "main.go/model/common/response" 9 | ) 10 | 11 | type MallIndexApi struct { 12 | } 13 | 14 | // MallIndexInfo 加载首页信息 15 | func (m *MallIndexApi) MallIndexInfo(c *gin.Context) { 16 | err, _, mallCarouseInfo := mallCarouselService.GetCarouselsForIndex(5) 17 | if err != nil { 18 | global.GVA_LOG.Error("轮播图获取失败"+err.Error(), zap.Error(err)) 19 | response.FailWithMessage("轮播图获取失败", c) 20 | } 21 | err, hotGoodses := mallIndexConfigService.GetConfigGoodsForIndex(enum.IndexGoodsHot.Code(), 4) 22 | if err != nil { 23 | global.GVA_LOG.Error("热销商品获取失败"+err.Error(), zap.Error(err)) 24 | response.FailWithMessage("热销商品获取失败", c) 25 | } 26 | err, newGoodses := mallIndexConfigService.GetConfigGoodsForIndex(enum.IndexGoodsNew.Code(), 5) 27 | if err != nil { 28 | global.GVA_LOG.Error("新品获取失败"+err.Error(), zap.Error(err)) 29 | response.FailWithMessage("新品获取失败", c) 30 | } 31 | err, recommendGoodses := mallIndexConfigService.GetConfigGoodsForIndex(enum.IndexGoodsRecommond.Code(), 10) 32 | if err != nil { 33 | global.GVA_LOG.Error("推荐商品获取失败"+err.Error(), zap.Error(err)) 34 | response.FailWithMessage("推荐商品获取失败", c) 35 | } 36 | indexResult := make(map[string]interface{}) 37 | indexResult["carousels"] = mallCarouseInfo 38 | indexResult["hotGoodses"] = hotGoodses 39 | indexResult["newGoodses"] = newGoodses 40 | indexResult["recommendGoodses"] = recommendGoodses 41 | response.OkWithData(indexResult, c) 42 | 43 | } 44 | -------------------------------------------------------------------------------- /api/v1/mall/mall_order.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/response" 8 | mallReq "main.go/model/mall/request" 9 | "main.go/utils" 10 | "strconv" 11 | ) 12 | 13 | type MallOrderApi struct { 14 | } 15 | 16 | func (m *MallOrderApi) SaveOrder(c *gin.Context) { 17 | var saveOrderParam mallReq.SaveOrderParam 18 | _ = c.ShouldBindJSON(&saveOrderParam) 19 | if err := utils.Verify(saveOrderParam, utils.SaveOrderParamVerify); err != nil { 20 | response.FailWithMessage(err.Error(), c) 21 | } 22 | token := c.GetHeader("token") 23 | 24 | priceTotal := 0 25 | err, itemsForSave := mallShopCartService.GetCartItemsForSettle(token, saveOrderParam.CartItemIds) 26 | if len(itemsForSave) < 1 { 27 | response.FailWithMessage("无数据:"+err.Error(), c) 28 | } else { 29 | //总价 30 | for _, newBeeMallShoppingCartItemVO := range itemsForSave { 31 | priceTotal = priceTotal + newBeeMallShoppingCartItemVO.GoodsCount*newBeeMallShoppingCartItemVO.SellingPrice 32 | } 33 | if priceTotal < 1 { 34 | response.FailWithMessage("价格异常", c) 35 | } 36 | _, userAddress := mallUserAddressService.GetMallUserDefaultAddress(token) 37 | if err, saveOrderResult := mallOrderService.SaveOrder(token, userAddress, itemsForSave); err != nil { 38 | global.GVA_LOG.Error("生成订单失败", zap.Error(err)) 39 | response.FailWithMessage("生成订单失败:"+err.Error(), c) 40 | } else { 41 | response.OkWithData(saveOrderResult, c) 42 | } 43 | } 44 | } 45 | 46 | func (m *MallOrderApi) PaySuccess(c *gin.Context) { 47 | orderNo := c.Query("orderNo") 48 | payType, _ := strconv.Atoi(c.Query("payType")) 49 | if err := mallOrderService.PaySuccess(orderNo, payType); err != nil { 50 | global.GVA_LOG.Error("订单支付失败", zap.Error(err)) 51 | response.FailWithMessage("订单支付失败:"+err.Error(), c) 52 | } 53 | response.OkWithMessage("订单支付成功", c) 54 | } 55 | 56 | func (m *MallOrderApi) FinishOrder(c *gin.Context) { 57 | orderNo := c.Param("orderNo") 58 | token := c.GetHeader("token") 59 | if err := mallOrderService.FinishOrder(token, orderNo); err != nil { 60 | global.GVA_LOG.Error("订单签收失败", zap.Error(err)) 61 | response.FailWithMessage("订单签收失败:"+err.Error(), c) 62 | } 63 | response.OkWithMessage("订单签收成功", c) 64 | 65 | } 66 | 67 | func (m *MallOrderApi) CancelOrder(c *gin.Context) { 68 | orderNo := c.Param("orderNo") 69 | token := c.GetHeader("token") 70 | if err := mallOrderService.CancelOrder(token, orderNo); err != nil { 71 | global.GVA_LOG.Error("订单签收失败", zap.Error(err)) 72 | response.FailWithMessage("订单签收失败:"+err.Error(), c) 73 | } 74 | response.OkWithMessage("订单签收成功", c) 75 | 76 | } 77 | func (m *MallOrderApi) OrderDetailPage(c *gin.Context) { 78 | orderNo := c.Param("orderNo") 79 | token := c.GetHeader("token") 80 | if err, orderDetail := mallOrderService.GetOrderDetailByOrderNo(token, orderNo); err != nil { 81 | global.GVA_LOG.Error("查询订单详情接口", zap.Error(err)) 82 | response.FailWithMessage("查询订单详情接口:"+err.Error(), c) 83 | } else { 84 | response.OkWithData(orderDetail, c) 85 | } 86 | } 87 | 88 | func (m *MallOrderApi) OrderList(c *gin.Context) { 89 | token := c.GetHeader("token") 90 | pageNumber, _ := strconv.Atoi(c.Query("pageNumber")) 91 | status := c.Query("status") 92 | if pageNumber <= 0 { 93 | pageNumber = 1 94 | } 95 | if err, list, total := mallOrderService.MallOrderListBySearch(token, pageNumber, status); err != nil { 96 | global.GVA_LOG.Error("查询失败!", zap.Error(err)) 97 | response.FailWithMessage("查询失败"+err.Error(), c) 98 | } else if len(list) < 1 { 99 | // 前端项目这里有一个取数逻辑,如果数组为空,数组需要为[] 不能是Null 100 | response.OkWithDetailed(response.PageResult{ 101 | List: make([]interface{}, 0), 102 | TotalCount: total, 103 | CurrPage: pageNumber, 104 | PageSize: 5, 105 | }, "SUCCESS", c) 106 | } else { 107 | response.OkWithDetailed(response.PageResult{ 108 | List: list, 109 | TotalCount: total, 110 | CurrPage: pageNumber, 111 | PageSize: 5, 112 | }, "SUCCESS", c) 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /api/v1/mall/mall_shop_cart.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/response" 8 | mallReq "main.go/model/mall/request" 9 | "main.go/utils" 10 | "strconv" 11 | ) 12 | 13 | type MallShopCartApi struct { 14 | } 15 | 16 | func (m *MallShopCartApi) CartItemList(c *gin.Context) { 17 | token := c.GetHeader("token") 18 | if err, shopCartItem := mallShopCartService.GetMyShoppingCartItems(token); err != nil { 19 | global.GVA_LOG.Error("获取购物车失败", zap.Error(err)) 20 | response.FailWithMessage("获取购物车失败:"+err.Error(), c) 21 | } else { 22 | response.OkWithData(shopCartItem, c) 23 | } 24 | } 25 | 26 | func (m *MallShopCartApi) SaveMallShoppingCartItem(c *gin.Context) { 27 | token := c.GetHeader("token") 28 | var req mallReq.SaveCartItemParam 29 | _ = c.ShouldBindJSON(&req) 30 | if err := mallShopCartService.SaveMallCartItem(token, req); err != nil { 31 | global.GVA_LOG.Error("添加购物车失败", zap.Error(err)) 32 | response.FailWithMessage("添加购物车失败:"+err.Error(), c) 33 | } 34 | response.OkWithMessage("添加购物车成功", c) 35 | } 36 | 37 | func (m *MallShopCartApi) UpdateMallShoppingCartItem(c *gin.Context) { 38 | token := c.GetHeader("token") 39 | var req mallReq.UpdateCartItemParam 40 | _ = c.ShouldBindJSON(&req) 41 | if err := mallShopCartService.UpdateMallCartItem(token, req); err != nil { 42 | global.GVA_LOG.Error("修改购物车失败", zap.Error(err)) 43 | response.FailWithMessage("修改购物车失败:"+err.Error(), c) 44 | } 45 | response.OkWithMessage("修改购物车成功", c) 46 | } 47 | 48 | func (m *MallShopCartApi) DelMallShoppingCartItem(c *gin.Context) { 49 | token := c.GetHeader("token") 50 | id, _ := strconv.Atoi(c.Param("newBeeMallShoppingCartItemId")) 51 | if err := mallShopCartService.DeleteMallCartItem(token, id); err != nil { 52 | global.GVA_LOG.Error("修改购物车失败", zap.Error(err)) 53 | response.FailWithMessage("修改购物车失败:"+err.Error(), c) 54 | } 55 | response.OkWithMessage("修改购物车成功", c) 56 | } 57 | 58 | func (m *MallShopCartApi) ToSettle(c *gin.Context) { 59 | cartItemIdsStr := c.Query("cartItemIds") 60 | token := c.GetHeader("token") 61 | cartItemIds := utils.StrToInt(cartItemIdsStr) 62 | if err, cartItemRes := mallShopCartService.GetCartItemsForSettle(token, cartItemIds); err != nil { 63 | global.GVA_LOG.Error("获取购物明细异常:", zap.Error(err)) 64 | response.FailWithMessage("获取购物明细异常:"+err.Error(), c) 65 | } else { 66 | response.OkWithData(cartItemRes, c) 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /api/v1/mall/mall_user.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/response" 8 | mallReq "main.go/model/mall/request" 9 | "main.go/utils" 10 | ) 11 | 12 | type MallUserApi struct { 13 | } 14 | 15 | func (m *MallUserApi) UserRegister(c *gin.Context) { 16 | var req mallReq.RegisterUserParam 17 | _ = c.ShouldBindJSON(&req) 18 | if err := utils.Verify(req, utils.MallUserRegisterVerify); err != nil { 19 | response.FailWithMessage(err.Error(), c) 20 | return 21 | } 22 | if err := mallUserService.RegisterUser(req); err != nil { 23 | global.GVA_LOG.Error("创建失败", zap.Error(err)) 24 | response.FailWithMessage("创建失败:"+err.Error(), c) 25 | } 26 | response.OkWithMessage("创建成功", c) 27 | } 28 | 29 | func (m *MallUserApi) UserInfoUpdate(c *gin.Context) { 30 | var req mallReq.UpdateUserInfoParam 31 | token := c.GetHeader("token") 32 | if err := mallUserService.UpdateUserInfo(token, req); err != nil { 33 | global.GVA_LOG.Error("更新用户信息失败", zap.Error(err)) 34 | response.FailWithMessage("更新用户信息失败"+err.Error(), c) 35 | } 36 | response.OkWithMessage("更新成功", c) 37 | } 38 | 39 | func (m *MallUserApi) GetUserInfo(c *gin.Context) { 40 | token := c.GetHeader("token") 41 | if err, userDetail := mallUserService.GetUserDetail(token); err != nil { 42 | global.GVA_LOG.Error("未查询到记录", zap.Error(err)) 43 | response.FailWithMessage("未查询到记录", c) 44 | } else { 45 | response.OkWithData(userDetail, c) 46 | } 47 | } 48 | 49 | func (m *MallUserApi) UserLogin(c *gin.Context) { 50 | var req mallReq.UserLoginParam 51 | _ = c.ShouldBindJSON(&req) 52 | if err, _, adminToken := mallUserService.UserLogin(req); err != nil { 53 | response.FailWithMessage("登陆失败", c) 54 | } else { 55 | response.OkWithData(adminToken.Token, c) 56 | } 57 | } 58 | 59 | func (m *MallUserApi) UserLogout(c *gin.Context) { 60 | token := c.GetHeader("token") 61 | if err := mallUserTokenService.DeleteMallUserToken(token); err != nil { 62 | response.FailWithMessage("登出失败", c) 63 | } else { 64 | response.OkWithMessage("登出成功", c) 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /api/v1/mall/mall_user_address.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/response" 8 | mallReq "main.go/model/mall/request" 9 | "strconv" 10 | ) 11 | 12 | type MallUserAddressApi struct { 13 | } 14 | 15 | func (m *MallUserAddressApi) AddressList(c *gin.Context) { 16 | token := c.GetHeader("token") 17 | if err, userAddressList := mallUserAddressService.GetMyAddress(token); err != nil { 18 | global.GVA_LOG.Error("获取地址失败", zap.Error(err)) 19 | response.FailWithMessage("获取地址失败:"+err.Error(), c) 20 | } else if len(userAddressList) == 0 { 21 | response.OkWithData(nil, c) 22 | } else { 23 | response.OkWithData(userAddressList, c) 24 | } 25 | } 26 | 27 | func (m *MallUserAddressApi) SaveUserAddress(c *gin.Context) { 28 | var req mallReq.AddAddressParam 29 | _ = c.ShouldBindJSON(&req) 30 | token := c.GetHeader("token") 31 | err := mallUserAddressService.SaveUserAddress(token, req) 32 | if err != nil { 33 | global.GVA_LOG.Error("创建失败", zap.Error(err)) 34 | response.FailWithMessage("创建失败:"+err.Error(), c) 35 | } 36 | response.OkWithMessage("创建成功", c) 37 | 38 | } 39 | 40 | func (m *MallUserAddressApi) UpdateMallUserAddress(c *gin.Context) { 41 | var req mallReq.UpdateAddressParam 42 | _ = c.ShouldBindJSON(&req) 43 | token := c.GetHeader("token") 44 | err := mallUserAddressService.UpdateUserAddress(token, req) 45 | if err != nil { 46 | global.GVA_LOG.Error("更新用户地址失败", zap.Error(err)) 47 | response.FailWithMessage("更新用户地址失败:"+err.Error(), c) 48 | } 49 | response.OkWithMessage("更新用户地址成功", c) 50 | } 51 | 52 | func (m *MallUserAddressApi) GetMallUserAddress(c *gin.Context) { 53 | id, _ := strconv.Atoi(c.Param("addressId")) 54 | token := c.GetHeader("token") 55 | if err, userAddress := mallUserAddressService.GetMallUserAddressById(token, id); err != nil { 56 | global.GVA_LOG.Error("获取地址失败", zap.Error(err)) 57 | response.FailWithMessage("获取地址失败:"+err.Error(), c) 58 | } else { 59 | response.OkWithData(userAddress, c) 60 | } 61 | } 62 | 63 | func (m *MallUserAddressApi) GetMallUserDefaultAddress(c *gin.Context) { 64 | token := c.GetHeader("token") 65 | if err, userAddress := mallUserAddressService.GetMallUserDefaultAddress(token); err != nil { 66 | global.GVA_LOG.Error("获取地址失败", zap.Error(err)) 67 | response.FailWithMessage("获取地址失败:"+err.Error(), c) 68 | } else { 69 | response.OkWithData(userAddress, c) 70 | } 71 | } 72 | 73 | func (m *MallUserAddressApi) DeleteUserAddress(c *gin.Context) { 74 | id, _ := strconv.Atoi(c.Param("addressId")) 75 | token := c.GetHeader("token") 76 | err := mallUserAddressService.DeleteUserAddress(token, id) 77 | if err != nil { 78 | global.GVA_LOG.Error("删除用户地址失败", zap.Error(err)) 79 | response.FailWithMessage("删除用户地址失败:"+err.Error(), c) 80 | } 81 | response.OkWithMessage("删除用户地址成功", c) 82 | 83 | } 84 | -------------------------------------------------------------------------------- /api/v1/manage/enter.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import "main.go/service" 4 | 5 | type ManageGroup struct { 6 | ManageAdminUserApi 7 | ManageGoodsCategoryApi 8 | ManageGoodsInfoApi 9 | ManageCarouselApi 10 | ManageIndexConfigApi 11 | ManageOrderApi 12 | } 13 | 14 | var mallAdminUserService = service.ServiceGroupApp.ManageServiceGroup.ManageAdminUserService 15 | var mallAdminUserTokenService = service.ServiceGroupApp.ManageServiceGroup.ManageAdminUserTokenService 16 | var mallUserService = service.ServiceGroupApp.ManageServiceGroup.ManageUserService 17 | var mallGoodsCategoryService = service.ServiceGroupApp.ManageServiceGroup.ManageGoodsCategoryService 18 | var fileUploadAndDownloadService = service.ServiceGroupApp.ExampleServiceGroup.FileUploadAndDownloadService 19 | var mallGoodsInfoService = service.ServiceGroupApp.ManageServiceGroup.ManageGoodsInfoService 20 | var mallCarouselService = service.ServiceGroupApp.ManageServiceGroup.ManageCarouselService 21 | var mallIndexConfigService = service.ServiceGroupApp.ManageServiceGroup.ManageIndexConfigService 22 | var mallOrderService = service.ServiceGroupApp.ManageServiceGroup.ManageOrderService 23 | -------------------------------------------------------------------------------- /api/v1/manage/manage_admin_user.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/request" 8 | "main.go/model/common/response" 9 | "main.go/model/example" 10 | "main.go/model/manage" 11 | manageReq "main.go/model/manage/request" 12 | "main.go/utils" 13 | "strconv" 14 | ) 15 | 16 | type ManageAdminUserApi struct { 17 | } 18 | 19 | // 创建AdminUser 20 | func (m *ManageAdminUserApi) CreateAdminUser(c *gin.Context) { 21 | var params manageReq.MallAdminParam 22 | _ = c.ShouldBindJSON(¶ms) 23 | if err := utils.Verify(params, utils.AdminUserRegisterVerify); err != nil { 24 | response.FailWithMessage(err.Error(), c) 25 | return 26 | } 27 | mallAdminUser := manage.MallAdminUser{ 28 | LoginUserName: params.LoginUserName, 29 | NickName: params.NickName, 30 | LoginPassword: utils.MD5V([]byte(params.LoginPassword)), 31 | } 32 | if err := mallAdminUserService.CreateMallAdminUser(mallAdminUser); err != nil { 33 | global.GVA_LOG.Error("创建失败:", zap.Error(err)) 34 | response.FailWithMessage("创建失败"+err.Error(), c) 35 | } else { 36 | response.OkWithMessage("创建成功", c) 37 | } 38 | } 39 | 40 | // 修改密码 41 | func (m *ManageAdminUserApi) UpdateAdminUserPassword(c *gin.Context) { 42 | var req manageReq.MallUpdatePasswordParam 43 | _ = c.ShouldBindJSON(&req) 44 | //mallAdminUserName := manage.MallAdminUser{ 45 | // LoginPassword: utils.MD5V([]byte(req.LoginPassword)), 46 | //} 47 | userToken := c.GetHeader("token") 48 | if err := mallAdminUserService.UpdateMallAdminPassWord(userToken, req); err != nil { 49 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 50 | response.FailWithMessage("更新失败:"+err.Error(), c) 51 | } else { 52 | response.OkWithMessage("更新成功", c) 53 | } 54 | 55 | } 56 | 57 | // 更新用户名 58 | func (m *ManageAdminUserApi) UpdateAdminUserName(c *gin.Context) { 59 | var req manageReq.MallUpdateNameParam 60 | _ = c.ShouldBindJSON(&req) 61 | userToken := c.GetHeader("token") 62 | if err := mallAdminUserService.UpdateMallAdminName(userToken, req); err != nil { 63 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 64 | response.FailWithMessage("更新失败", c) 65 | } else { 66 | response.OkWithMessage("更新成功", c) 67 | } 68 | } 69 | 70 | // AdminUserProfile 用id查询AdminUser 71 | func (m *ManageAdminUserApi) AdminUserProfile(c *gin.Context) { 72 | adminToken := c.GetHeader("token") 73 | if err, mallAdminUser := mallAdminUserService.GetMallAdminUser(adminToken); err != nil { 74 | global.GVA_LOG.Error("未查询到记录", zap.Error(err)) 75 | response.FailWithMessage("未查询到记录", c) 76 | } else { 77 | mallAdminUser.LoginPassword = "******" 78 | response.OkWithData(mallAdminUser, c) 79 | } 80 | } 81 | 82 | // AdminLogin 管理员登陆 83 | func (m *ManageAdminUserApi) AdminLogin(c *gin.Context) { 84 | var adminLoginParams manageReq.MallAdminLoginParam 85 | _ = c.ShouldBindJSON(&adminLoginParams) 86 | if err, _, adminToken := mallAdminUserService.AdminLogin(adminLoginParams); err != nil { 87 | response.FailWithMessage("登陆失败", c) 88 | } else { 89 | response.OkWithData(adminToken.Token, c) 90 | } 91 | } 92 | 93 | // AdminLogout 登出 94 | func (m *ManageAdminUserApi) AdminLogout(c *gin.Context) { 95 | token := c.GetHeader("token") 96 | if err := mallAdminUserTokenService.DeleteMallAdminUserToken(token); err != nil { 97 | response.FailWithMessage("登出失败", c) 98 | } else { 99 | response.OkWithMessage("登出成功", c) 100 | } 101 | 102 | } 103 | 104 | // UserList 商城注册用户列表 105 | func (m *ManageAdminUserApi) UserList(c *gin.Context) { 106 | var pageInfo manageReq.MallUserSearch 107 | _ = c.ShouldBindQuery(&pageInfo) 108 | if err, list, total := mallUserService.GetMallUserInfoList(pageInfo); err != nil { 109 | global.GVA_LOG.Error("获取失败!", zap.Error(err)) 110 | response.FailWithMessage("获取失败", c) 111 | } else { 112 | response.OkWithDetailed(response.PageResult{ 113 | List: list, 114 | TotalCount: total, 115 | CurrPage: pageInfo.PageNumber, 116 | PageSize: pageInfo.PageSize, 117 | }, "获取成功", c) 118 | } 119 | } 120 | 121 | // LockUser 用户禁用与解除禁用(0-未锁定 1-已锁定) 122 | func (m *ManageAdminUserApi) LockUser(c *gin.Context) { 123 | lockStatus, _ := strconv.Atoi(c.Param("lockStatus")) 124 | var IDS request.IdsReq 125 | _ = c.ShouldBindJSON(&IDS) 126 | if err := mallUserService.LockUser(IDS, lockStatus); err != nil { 127 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 128 | response.FailWithMessage("更新失败", c) 129 | } else { 130 | response.OkWithMessage("更新成功", c) 131 | } 132 | } 133 | 134 | // UploadFile 上传单图 135 | // 此处上传图片的功能可用,但是任然使用原前端项目的接口指向的地址是 136 | func (m *ManageAdminUserApi) UploadFile(c *gin.Context) { 137 | var file example.ExaFileUploadAndDownload 138 | noSave := c.DefaultQuery("noSave", "0") 139 | _, header, err := c.Request.FormFile("file") 140 | if err != nil { 141 | global.GVA_LOG.Error("接收文件失败!", zap.Error(err)) 142 | response.FailWithMessage("接收文件失败", c) 143 | return 144 | } 145 | err, file = fileUploadAndDownloadService.UploadFile(header, noSave) // 文件上传后拿到文件路径 146 | if err != nil { 147 | global.GVA_LOG.Error("修改数据库链接失败!", zap.Error(err)) 148 | response.FailWithMessage("修改数据库链接失败", c) 149 | return 150 | } 151 | //这里直接使用本地的url 152 | response.OkWithData("http://localhost:8888/"+file.Url, c) 153 | } 154 | -------------------------------------------------------------------------------- /api/v1/manage/manage_carousel.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/request" 8 | "main.go/model/common/response" 9 | manageReq "main.go/model/manage/request" 10 | "strconv" 11 | ) 12 | 13 | type ManageCarouselApi struct { 14 | } 15 | 16 | func (m *ManageCarouselApi) CreateCarousel(c *gin.Context) { 17 | var req manageReq.MallCarouselAddParam 18 | _ = c.ShouldBindJSON(&req) 19 | if err := mallCarouselService.CreateCarousel(req); err != nil { 20 | global.GVA_LOG.Error("创建失败!", zap.Error(err)) 21 | response.FailWithMessage("创建失败"+err.Error(), c) 22 | } else { 23 | response.OkWithMessage("创建成功", c) 24 | } 25 | } 26 | 27 | func (m *ManageCarouselApi) DeleteCarousel(c *gin.Context) { 28 | var ids request.IdsReq 29 | _ = c.ShouldBindJSON(&ids) 30 | if err := mallCarouselService.DeleteCarousel(ids); err != nil { 31 | global.GVA_LOG.Error("删除失败!", zap.Error(err)) 32 | response.FailWithMessage("删除失败"+err.Error(), c) 33 | } else { 34 | response.OkWithMessage("删除成功", c) 35 | } 36 | } 37 | 38 | func (m *ManageCarouselApi) UpdateCarousel(c *gin.Context) { 39 | var req manageReq.MallCarouselUpdateParam 40 | _ = c.ShouldBindJSON(&req) 41 | if err := mallCarouselService.UpdateCarousel(req); err != nil { 42 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 43 | response.FailWithMessage("更新失败:"+err.Error(), c) 44 | } else { 45 | response.OkWithMessage("更新成功", c) 46 | } 47 | } 48 | 49 | // FindMallCarousel 用id查询MallCarousel 50 | func (m *ManageCarouselApi) FindCarousel(c *gin.Context) { 51 | id, _ := strconv.Atoi(c.Param("id")) 52 | if err, mallCarousel := mallCarouselService.GetCarousel(id); err != nil { 53 | global.GVA_LOG.Error("查询失败!"+err.Error(), zap.Error(err)) 54 | response.FailWithMessage("查询失败", c) 55 | } else { 56 | response.OkWithData(mallCarousel, c) 57 | } 58 | } 59 | 60 | // GetMallCarouselList 分页获取MallCarousel列表 61 | func (m *ManageCarouselApi) GetCarouselList(c *gin.Context) { 62 | var pageInfo manageReq.MallCarouselSearch 63 | _ = c.ShouldBindQuery(&pageInfo) 64 | if err, list, total := mallCarouselService.GetCarouselInfoList(pageInfo); err != nil { 65 | global.GVA_LOG.Error("获取失败!"+err.Error(), zap.Error(err)) 66 | response.FailWithMessage("获取失败", c) 67 | } else { 68 | response.OkWithDetailed(response.PageResult{ 69 | List: list, 70 | TotalCount: total, 71 | CurrPage: pageInfo.PageNumber, 72 | PageSize: pageInfo.PageSize, 73 | }, "获取成功", c) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /api/v1/manage/manage_goods_category.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/enum" 8 | "main.go/model/common/request" 9 | "main.go/model/common/response" 10 | manageReq "main.go/model/manage/request" 11 | manageRes "main.go/model/manage/response" 12 | "strconv" 13 | ) 14 | 15 | type ManageGoodsCategoryApi struct { 16 | } 17 | 18 | // CreateCategory 新建商品分类 19 | func (g *ManageGoodsCategoryApi) CreateCategory(c *gin.Context) { 20 | var category manageReq.MallGoodsCategoryReq 21 | _ = c.ShouldBindJSON(&category) 22 | if err := mallGoodsCategoryService.AddCategory(category); err != nil { 23 | global.GVA_LOG.Error("创建失败", zap.Error(err)) 24 | response.FailWithMessage("创建失败:"+err.Error(), c) 25 | } else { 26 | response.OkWithMessage("创建成功", c) 27 | } 28 | } 29 | 30 | // UpdateCategory 修改商品分类信息 31 | func (g *ManageGoodsCategoryApi) UpdateCategory(c *gin.Context) { 32 | var category manageReq.MallGoodsCategoryReq 33 | _ = c.ShouldBindJSON(&category) 34 | if err := mallGoodsCategoryService.UpdateCategory(category); err != nil { 35 | global.GVA_LOG.Error("更新失败", zap.Error(err)) 36 | response.FailWithMessage("更新失败,存在相同分类", c) 37 | } else { 38 | response.OkWithMessage("更新成功", c) 39 | } 40 | } 41 | 42 | // GetCategoryList 获取商品分类 43 | func (g *ManageGoodsCategoryApi) GetCategoryList(c *gin.Context) { 44 | var req manageReq.SearchCategoryParams 45 | _ = c.ShouldBindQuery(&req) 46 | if err, list, total := mallGoodsCategoryService.SelectCategoryPage(req); err != nil { 47 | global.GVA_LOG.Error("获取失败!", zap.Error(err)) 48 | response.FailWithMessage("获取失败:"+err.Error(), c) 49 | } else { 50 | response.OkWithData(response.PageResult{ 51 | List: list, 52 | TotalCount: total, 53 | CurrPage: req.PageNumber, 54 | PageSize: req.PageSize, 55 | TotalPage: int(total) / req.PageSize, 56 | }, c) 57 | } 58 | } 59 | 60 | // GetCategory 通过id获取分类数据 61 | func (g *ManageGoodsCategoryApi) GetCategory(c *gin.Context) { 62 | id, _ := strconv.Atoi(c.Param("id")) 63 | err, goodsCategory := mallGoodsCategoryService.SelectCategoryById(id) 64 | if err != nil { 65 | global.GVA_LOG.Error("获取失败!", zap.Error(err)) 66 | response.FailWithMessage("获取失败:"+err.Error(), c) 67 | } else { 68 | response.OkWithData(manageRes.GoodsCategoryResponse{GoodsCategory: goodsCategory}, c) 69 | } 70 | } 71 | 72 | // DelCategory 设置分类失效 73 | func (g *ManageGoodsCategoryApi) DelCategory(c *gin.Context) { 74 | var ids request.IdsReq 75 | _ = c.ShouldBindJSON(&ids) 76 | if err, _ := mallGoodsCategoryService.DeleteGoodsCategoriesByIds(ids); err != nil { 77 | global.GVA_LOG.Error("删除失败!", zap.Error(err)) 78 | response.FailWithMessage("删除失败"+err.Error(), c) 79 | } else { 80 | response.OkWithMessage("删除成功", c) 81 | } 82 | 83 | } 84 | 85 | // ListForSelect 用于三级分类联动效果制作 86 | func (g *ManageGoodsCategoryApi) ListForSelect(c *gin.Context) { 87 | id, _ := strconv.Atoi(c.Param("id")) 88 | err, goodsCategory := mallGoodsCategoryService.SelectCategoryById(id) 89 | if err != nil { 90 | global.GVA_LOG.Error("获取失败!", zap.Error(err)) 91 | response.FailWithMessage("获取失败"+err.Error(), c) 92 | } 93 | level := goodsCategory.CategoryLevel 94 | if level == enum.LevelThree.Code() || 95 | level == enum.Default.Code() { 96 | response.FailWithMessage("参数异常", c) 97 | } 98 | categoryResult := make(map[string]interface{}) 99 | if level == enum.LevelOne.Code() { 100 | _, levelTwoList := mallGoodsCategoryService.SelectByLevelAndParentIdsAndNumber(id, enum.LevelTwo.Code()) 101 | if levelTwoList != nil { 102 | _, levelThreeList := mallGoodsCategoryService.SelectByLevelAndParentIdsAndNumber(int(levelTwoList[0].CategoryId), enum.LevelThree.Code()) 103 | categoryResult["secondLevelCategories"] = levelTwoList 104 | categoryResult["thirdLevelCategories"] = levelThreeList 105 | } 106 | } 107 | if level == enum.LevelTwo.Code() { 108 | _, levelThreeList := mallGoodsCategoryService.SelectByLevelAndParentIdsAndNumber(id, enum.LevelThree.Code()) 109 | categoryResult["thirdLevelCategories"] = levelThreeList 110 | } 111 | response.OkWithData(categoryResult, c) 112 | } 113 | -------------------------------------------------------------------------------- /api/v1/manage/manage_goods_info.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/request" 8 | "main.go/model/common/response" 9 | "main.go/model/manage" 10 | manageReq "main.go/model/manage/request" 11 | "strconv" 12 | ) 13 | 14 | type ManageGoodsInfoApi struct { 15 | } 16 | 17 | func (m *ManageGoodsInfoApi) CreateGoodsInfo(c *gin.Context) { 18 | var mallGoodsInfo manageReq.GoodsInfoAddParam 19 | _ = c.ShouldBindJSON(&mallGoodsInfo) 20 | if err := mallGoodsInfoService.CreateMallGoodsInfo(mallGoodsInfo); err != nil { 21 | global.GVA_LOG.Error("创建失败!", zap.Error(err)) 22 | response.FailWithMessage("创建失败!"+err.Error(), c) 23 | } else { 24 | response.OkWithMessage("创建成功", c) 25 | } 26 | } 27 | 28 | // DeleteMallGoodsInfo 删除MallGoodsInfo 29 | func (m *ManageGoodsInfoApi) DeleteGoodsInfo(c *gin.Context) { 30 | var mallGoodsInfo manage.MallGoodsInfo 31 | _ = c.ShouldBindJSON(&mallGoodsInfo) 32 | if err := mallGoodsInfoService.DeleteMallGoodsInfo(mallGoodsInfo); err != nil { 33 | global.GVA_LOG.Error("删除失败!", zap.Error(err)) 34 | response.FailWithMessage("删除失败"+err.Error(), c) 35 | } else { 36 | response.OkWithMessage("删除成功", c) 37 | } 38 | } 39 | 40 | // ChangeMallGoodsInfoByIds 批量删除MallGoodsInfo 41 | func (m *ManageGoodsInfoApi) ChangeGoodsInfoByIds(c *gin.Context) { 42 | var IDS request.IdsReq 43 | _ = c.ShouldBindJSON(&IDS) 44 | sellStatus := c.Param("status") 45 | if err := mallGoodsInfoService.ChangeMallGoodsInfoByIds(IDS, sellStatus); err != nil { 46 | global.GVA_LOG.Error("修改商品状态失败!", zap.Error(err)) 47 | response.FailWithMessage("修改商品状态失败"+err.Error(), c) 48 | } else { 49 | response.OkWithMessage("修改商品状态成功", c) 50 | } 51 | } 52 | 53 | // UpdateMallGoodsInfo 更新MallGoodsInfo 54 | func (m *ManageGoodsInfoApi) UpdateGoodsInfo(c *gin.Context) { 55 | var mallGoodsInfo manageReq.GoodsInfoUpdateParam 56 | _ = c.ShouldBindJSON(&mallGoodsInfo) 57 | if err := mallGoodsInfoService.UpdateMallGoodsInfo(mallGoodsInfo); err != nil { 58 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 59 | response.FailWithMessage("更新失败"+err.Error(), c) 60 | } else { 61 | response.OkWithMessage("更新成功", c) 62 | } 63 | } 64 | 65 | // FindMallGoodsInfo 用id查询MallGoodsInfo 66 | func (m *ManageGoodsInfoApi) FindGoodsInfo(c *gin.Context) { 67 | id, _ := strconv.Atoi(c.Param("id")) 68 | err, goodsInfo := mallGoodsInfoService.GetMallGoodsInfo(id) 69 | if err != nil { 70 | global.GVA_LOG.Error("查询失败!", zap.Error(err)) 71 | response.FailWithMessage("查询失败"+err.Error(), c) 72 | } 73 | goodsInfoRes := make(map[string]interface{}) 74 | goodsInfoRes["goods"] = goodsInfo 75 | if _, thirdCategory := mallGoodsCategoryService.SelectCategoryById(goodsInfo.GoodsCategoryId); thirdCategory != (manage.MallGoodsCategory{}) { 76 | goodsInfoRes["thirdCategory"] = thirdCategory 77 | if _, secondCategory := mallGoodsCategoryService.SelectCategoryById(thirdCategory.ParentId); secondCategory != (manage.MallGoodsCategory{}) { 78 | goodsInfoRes["secondCategory"] = secondCategory 79 | if _, firstCategory := mallGoodsCategoryService.SelectCategoryById(secondCategory.ParentId); firstCategory != (manage.MallGoodsCategory{}) { 80 | goodsInfoRes["firstCategory"] = firstCategory 81 | } 82 | } 83 | } 84 | response.OkWithData(goodsInfoRes, c) 85 | 86 | } 87 | 88 | // GetMallGoodsInfoList 分页获取MallGoodsInfo列表 89 | func (m *ManageGoodsInfoApi) GetGoodsInfoList(c *gin.Context) { 90 | var pageInfo manageReq.MallGoodsInfoSearch 91 | _ = c.ShouldBindQuery(&pageInfo) 92 | goodsName := c.Query("goodsName") 93 | goodsSellStatus := c.Query("goodsSellStatus") 94 | if err, list, total := mallGoodsInfoService.GetMallGoodsInfoInfoList(pageInfo, goodsName, goodsSellStatus); err != nil { 95 | global.GVA_LOG.Error("获取失败!", zap.Error(err)) 96 | response.FailWithMessage("获取失败"+err.Error(), c) 97 | } else { 98 | response.OkWithDetailed(response.PageResult{ 99 | List: list, 100 | TotalCount: total, 101 | CurrPage: pageInfo.PageNumber, 102 | PageSize: pageInfo.PageSize, 103 | }, "获取成功", c) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /api/v1/manage/manage_index_config.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/request" 8 | "main.go/model/common/response" 9 | manageReq "main.go/model/manage/request" 10 | "strconv" 11 | ) 12 | 13 | type ManageIndexConfigApi struct { 14 | } 15 | 16 | func (m *ManageIndexConfigApi) CreateIndexConfig(c *gin.Context) { 17 | var req manageReq.MallIndexConfigAddParams 18 | _ = c.ShouldBindJSON(&req) 19 | if err := mallIndexConfigService.CreateMallIndexConfig(req); err != nil { 20 | global.GVA_LOG.Error("创建失败!", zap.Error(err)) 21 | response.FailWithMessage("创建失败"+err.Error(), c) 22 | } else { 23 | response.OkWithMessage("创建成功", c) 24 | } 25 | } 26 | 27 | func (m *ManageIndexConfigApi) DeleteIndexConfig(c *gin.Context) { 28 | var ids request.IdsReq 29 | _ = c.ShouldBindJSON(&ids) 30 | if err := mallIndexConfigService.DeleteMallIndexConfig(ids); err != nil { 31 | global.GVA_LOG.Error("删除失败!", zap.Error(err)) 32 | response.FailWithMessage("删除失败"+err.Error(), c) 33 | } else { 34 | response.OkWithMessage("删除成功", c) 35 | } 36 | } 37 | 38 | func (m *ManageIndexConfigApi) UpdateIndexConfig(c *gin.Context) { 39 | var req manageReq.MallIndexConfigUpdateParams 40 | _ = c.ShouldBindJSON(&req) 41 | if err := mallIndexConfigService.UpdateMallIndexConfig(req); err != nil { 42 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 43 | response.FailWithMessage("更新失败:"+err.Error(), c) 44 | } else { 45 | response.OkWithMessage("更新成功", c) 46 | } 47 | } 48 | 49 | func (m *ManageIndexConfigApi) FindIndexConfig(c *gin.Context) { 50 | id, _ := strconv.Atoi(c.Param("id")) 51 | if err, mallIndexConfig := mallIndexConfigService.GetMallIndexConfig(uint(id)); err != nil { 52 | global.GVA_LOG.Error("查询失败!"+err.Error(), zap.Error(err)) 53 | response.FailWithMessage("查询失败", c) 54 | } else { 55 | response.OkWithData(mallIndexConfig, c) 56 | } 57 | } 58 | 59 | func (m *ManageIndexConfigApi) GetIndexConfigList(c *gin.Context) { 60 | var pageInfo manageReq.MallIndexConfigSearch 61 | _ = c.ShouldBindQuery(&pageInfo) 62 | if err, list, total := mallIndexConfigService.GetMallIndexConfigInfoList(pageInfo); err != nil { 63 | global.GVA_LOG.Error("获取失败!"+err.Error(), zap.Error(err)) 64 | response.FailWithMessage("获取失败", c) 65 | } else { 66 | response.OkWithDetailed(response.PageResult{ 67 | List: list, 68 | TotalCount: total, 69 | CurrPage: pageInfo.PageNumber, 70 | PageSize: pageInfo.PageSize, 71 | }, "获取成功", c) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /api/v1/manage/manage_order.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "go.uber.org/zap" 6 | "main.go/global" 7 | "main.go/model/common/request" 8 | "main.go/model/common/response" 9 | ) 10 | 11 | type ManageOrderApi struct { 12 | } 13 | 14 | // CheckDoneOrder 发货 15 | func (m *ManageOrderApi) CheckDoneOrder(c *gin.Context) { 16 | var IDS request.IdsReq 17 | _ = c.ShouldBindJSON(&IDS) 18 | if err := mallOrderService.CheckDone(IDS); err != nil { 19 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 20 | response.FailWithMessage("更新失败", c) 21 | } else { 22 | response.OkWithMessage("更新成功", c) 23 | } 24 | } 25 | 26 | // CheckOutOrder 出库 27 | func (m *ManageOrderApi) CheckOutOrder(c *gin.Context) { 28 | var IDS request.IdsReq 29 | _ = c.ShouldBindJSON(&IDS) 30 | if err := mallOrderService.CheckOut(IDS); err != nil { 31 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 32 | response.FailWithMessage("更新失败", c) 33 | } else { 34 | response.OkWithMessage("更新成功", c) 35 | } 36 | } 37 | 38 | // CloseOrder 出库 39 | func (m *ManageOrderApi) CloseOrder(c *gin.Context) { 40 | var IDS request.IdsReq 41 | _ = c.ShouldBindJSON(&IDS) 42 | if err := mallOrderService.CloseOrder(IDS); err != nil { 43 | global.GVA_LOG.Error("更新失败!", zap.Error(err)) 44 | response.FailWithMessage("更新失败", c) 45 | } else { 46 | response.OkWithMessage("更新成功", c) 47 | } 48 | } 49 | 50 | // FindMallOrder 用id查询MallOrder 51 | func (m *ManageOrderApi) FindMallOrder(c *gin.Context) { 52 | id := c.Param("orderId") 53 | if err, newBeeMallOrderDetailVO := mallOrderService.GetMallOrder(id); err != nil { 54 | global.GVA_LOG.Error("查询失败!", zap.Error(err)) 55 | response.FailWithMessage("查询失败", c) 56 | } else { 57 | response.OkWithData(newBeeMallOrderDetailVO, c) 58 | } 59 | } 60 | 61 | // GetMallOrderList 分页获取MallOrder列表 62 | func (m *ManageOrderApi) GetMallOrderList(c *gin.Context) { 63 | var pageInfo request.PageInfo 64 | _ = c.ShouldBindQuery(&pageInfo) 65 | orderNo := c.Query("orderNo") 66 | orderStatus := c.Query("orderStatus") 67 | if err, list, total := mallOrderService.GetMallOrderInfoList(pageInfo, orderNo, orderStatus); err != nil { 68 | global.GVA_LOG.Error("获取失败!", zap.Error(err)) 69 | response.FailWithMessage("获取失败", c) 70 | } else { 71 | response.OkWithDetailed(response.PageResult{ 72 | List: list, 73 | TotalCount: total, 74 | CurrPage: pageInfo.PageNumber, 75 | PageSize: pageInfo.PageSize, 76 | }, "获取成功", c) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | ## 本地图片上传路径 2 | local: 3 | path: static 4 | mysql: 5 | path: 127.0.0.1 6 | port: "3306" 7 | config: charset=utf8mb4&parseTime=True&loc=Local 8 | db-name: newbee_mall_db_v2 9 | username: root 10 | password: root 11 | max-idle-conns: 0 12 | max-open-conns: 0 13 | log-mode: "" 14 | log-zap: false 15 | system: 16 | addr: 8888 17 | db-type: mysql 18 | oss-type: local 19 | use-multipoint: false 20 | iplimit-count: 15000 21 | iplimit-time: 3600 22 | zap: 23 | level: info 24 | format: console 25 | prefix: '[newbee_mall]' 26 | director: log 27 | showLine: true 28 | encode-level: LowercaseColorLevelEncoder 29 | stacktrace-key: stacktrace 30 | log-in-console: true 31 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type Server struct { 4 | Zap Zap `mapstructure:"zap" json:"zap" yaml:"zap"` 5 | System System `mapstructure:"system" json:"system" yaml:"system"` 6 | // gorm 7 | Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"` 8 | // oss 9 | Local Local `mapstructure:"local" json:"local" yaml:"local"` 10 | } 11 | -------------------------------------------------------------------------------- /config/mysql.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type Mysql struct { 4 | Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址 5 | Port string `mapstructure:"port" json:"port" yaml:"port"` // 端口 6 | Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置 7 | Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"` // 数据库名 8 | Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名 9 | Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码 10 | MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` // 空闲中的最大连接数 11 | MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` // 打开到数据库的最大连接数 12 | LogMode string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` // 是否开启Gorm全局日志 13 | LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` // 是否通过zap写入日志文件 14 | } 15 | 16 | func (m *Mysql) Dsn() string { 17 | return m.Username + ":" + m.Password + "@tcp(" + m.Path + ":" + m.Port + ")/" + m.Dbname + "?" + m.Config 18 | } 19 | -------------------------------------------------------------------------------- /config/oss.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type Local struct { 4 | Path string `mapstructure:"path" json:"path" yaml:"path"` // 本地文件路径 5 | } 6 | -------------------------------------------------------------------------------- /config/system.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type System struct { 4 | Env string `mapstructure:"env" json:"env" yaml:"env"` // 环境值 5 | Addr int `mapstructure:"addr" json:"addr" yaml:"addr"` // 端口值 6 | DbType string `mapstructure:"db-type" json:"dbType" yaml:"db-type"` // 数据库类型:mysql(默认)|sqlite|sqlserver|postgresql 7 | OssType string `mapstructure:"oss-type" json:"ossType" yaml:"oss-type"` // Oss类型 8 | UseMultipoint bool `mapstructure:"use-multipoint" json:"useMultipoint" yaml:"use-multipoint"` // 多点登录拦截 9 | LimitCountIP int `mapstructure:"iplimit-count" json:"iplimitCount" yaml:"iplimit-count"` 10 | LimitTimeIP int `mapstructure:"iplimit-time" json:"iplimitTime" yaml:"iplimit-time"` 11 | } 12 | -------------------------------------------------------------------------------- /config/zap.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type Zap struct { 4 | Level string `mapstructure:"level" json:"level" yaml:"level"` // 级别 5 | Format string `mapstructure:"format" json:"format" yaml:"format"` // 输出 6 | Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // 日志前缀 7 | Director string `mapstructure:"director" json:"director" yaml:"director"` // 日志文件夹 8 | ShowLine bool `mapstructure:"show-line" json:"showLine" yaml:"showLine"` // 显示行 9 | EncodeLevel string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level"` // 编码级 10 | StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key"` // 栈名 11 | LogInConsole bool `mapstructure:"log-in-console" json:"logInConsole" yaml:"log-in-console"` // 输出控制台 12 | } 13 | -------------------------------------------------------------------------------- /core/server.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "fmt" 5 | "main.go/global" 6 | "main.go/initialize" 7 | "time" 8 | 9 | "go.uber.org/zap" 10 | ) 11 | 12 | type server interface { 13 | ListenAndServe() error 14 | } 15 | 16 | func RunWindowsServer() { 17 | //if global.GVA_CONFIG.System.UseMultipoint { 18 | // // 初始化redis服务 19 | // initialize.Redis() 20 | //} 21 | 22 | //// 从db加载jwt数据 23 | //if global.GVA_DB != nil { 24 | // system.LoadAll() 25 | //} 26 | 27 | Router := initialize.Routers() 28 | 29 | //Router.Static("/form-generator", "./resource/page") 30 | 31 | address := fmt.Sprintf(":%d", global.GVA_CONFIG.System.Addr) 32 | s := initServer(address, Router) 33 | // 保证文本顺序输出 34 | // In order to ensure that the text order output can be deleted 35 | time.Sleep(10 * time.Microsecond) 36 | global.GVA_LOG.Info("server run success on ", zap.String("address", address)) 37 | 38 | global.GVA_LOG.Error(s.ListenAndServe().Error()) 39 | } 40 | -------------------------------------------------------------------------------- /core/server_other.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | // +build !windows 3 | 4 | package core 5 | 6 | import ( 7 | "github.com/fvbock/endless" 8 | "github.com/gin-gonic/gin" 9 | "time" 10 | ) 11 | 12 | func initServer(address string, router *gin.Engine) server { 13 | s := endless.NewServer(address, router) 14 | s.ReadHeaderTimeout = 20 * time.Second 15 | s.WriteTimeout = 20 * time.Second 16 | s.MaxHeaderBytes = 1 << 20 17 | return s 18 | } 19 | -------------------------------------------------------------------------------- /core/server_win.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | // +build windows 3 | 4 | package core 5 | 6 | import ( 7 | "github.com/gin-gonic/gin" 8 | "net/http" 9 | "time" 10 | ) 11 | 12 | func initServer(address string, router *gin.Engine) server { 13 | return &http.Server{ 14 | Addr: address, 15 | Handler: router, 16 | ReadTimeout: 20 * time.Second, 17 | WriteTimeout: 20 * time.Second, 18 | MaxHeaderBytes: 1 << 20, 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /core/viper.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "github.com/fsnotify/fsnotify" 7 | "github.com/spf13/viper" 8 | "main.go/global" 9 | "main.go/utils" 10 | "os" 11 | ) 12 | 13 | func Viper(path ...string) *viper.Viper { 14 | var config string 15 | if len(path) == 0 { 16 | flag.StringVar(&config, "c", "", "choose config file.") 17 | flag.Parse() 18 | if config == "" { // 优先级: 命令行 > 环境变量 > 默认值 19 | if configEnv := os.Getenv(utils.ConfigEnv); configEnv == "" { 20 | config = utils.ConfigFile 21 | fmt.Printf("您正在使用config的默认值,config的路径为%v\n", utils.ConfigFile) 22 | } else { 23 | config = configEnv 24 | fmt.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", config) 25 | } 26 | } else { 27 | fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config) 28 | } 29 | } else { 30 | config = path[0] 31 | fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config) 32 | } 33 | 34 | v := viper.New() 35 | v.SetConfigFile(config) 36 | v.SetConfigType("yaml") 37 | err := v.ReadInConfig() 38 | if err != nil { 39 | panic(fmt.Errorf("Fatal error config file: %s \n", err)) 40 | } 41 | v.WatchConfig() 42 | 43 | v.OnConfigChange(func(e fsnotify.Event) { 44 | fmt.Println("config file changed:", e.Name) 45 | if err := v.Unmarshal(&global.GVA_CONFIG); err != nil { 46 | fmt.Println(err) 47 | } 48 | }) 49 | if err := v.Unmarshal(&global.GVA_CONFIG); err != nil { 50 | fmt.Println(err) 51 | } 52 | return v 53 | } 54 | -------------------------------------------------------------------------------- /core/zap.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "fmt" 5 | "go.uber.org/zap" 6 | "go.uber.org/zap/zapcore" 7 | "main.go/global" 8 | "main.go/utils" 9 | "os" 10 | "time" 11 | ) 12 | 13 | func Zap() (logger *zap.Logger) { 14 | if ok, _ := utils.PathExists(global.GVA_CONFIG.Zap.Director); !ok { // 判断是否有Director文件夹 15 | fmt.Printf("create %v directory\n", global.GVA_CONFIG.Zap.Director) 16 | _ = os.Mkdir(global.GVA_CONFIG.Zap.Director, os.ModePerm) 17 | } 18 | // 调试级别 19 | debugPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool { 20 | return lev == zap.DebugLevel 21 | }) 22 | // 日志级别 23 | infoPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool { 24 | return lev == zap.InfoLevel 25 | }) 26 | // 警告级别 27 | warnPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool { 28 | return lev == zap.WarnLevel 29 | }) 30 | // 错误级别 31 | errorPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool { 32 | return lev >= zap.ErrorLevel 33 | }) 34 | 35 | cores := [...]zapcore.Core{ 36 | getEncoderCore(fmt.Sprintf("./%s/server_debug.log", global.GVA_CONFIG.Zap.Director), debugPriority), 37 | getEncoderCore(fmt.Sprintf("./%s/server_info.log", global.GVA_CONFIG.Zap.Director), infoPriority), 38 | getEncoderCore(fmt.Sprintf("./%s/server_warn.log", global.GVA_CONFIG.Zap.Director), warnPriority), 39 | getEncoderCore(fmt.Sprintf("./%s/server_error.log", global.GVA_CONFIG.Zap.Director), errorPriority), 40 | } 41 | logger = zap.New(zapcore.NewTee(cores[:]...), zap.AddCaller()) 42 | 43 | if global.GVA_CONFIG.Zap.ShowLine { 44 | logger = logger.WithOptions(zap.AddCaller()) 45 | } 46 | return logger 47 | } 48 | 49 | // getEncoderConfig 获取zapcore.EncoderConfig 50 | func getEncoderConfig() (config zapcore.EncoderConfig) { 51 | config = zapcore.EncoderConfig{ 52 | MessageKey: "message", 53 | LevelKey: "level", 54 | TimeKey: "time", 55 | NameKey: "logger", 56 | CallerKey: "caller", 57 | StacktraceKey: global.GVA_CONFIG.Zap.StacktraceKey, 58 | LineEnding: zapcore.DefaultLineEnding, 59 | EncodeLevel: zapcore.LowercaseLevelEncoder, 60 | EncodeTime: CustomTimeEncoder, 61 | EncodeDuration: zapcore.SecondsDurationEncoder, 62 | EncodeCaller: zapcore.FullCallerEncoder, 63 | } 64 | switch { 65 | case global.GVA_CONFIG.Zap.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认) 66 | config.EncodeLevel = zapcore.LowercaseLevelEncoder 67 | case global.GVA_CONFIG.Zap.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色 68 | config.EncodeLevel = zapcore.LowercaseColorLevelEncoder 69 | case global.GVA_CONFIG.Zap.EncodeLevel == "CapitalLevelEncoder": // 大写编码器 70 | config.EncodeLevel = zapcore.CapitalLevelEncoder 71 | case global.GVA_CONFIG.Zap.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色 72 | config.EncodeLevel = zapcore.CapitalColorLevelEncoder 73 | default: 74 | config.EncodeLevel = zapcore.LowercaseLevelEncoder 75 | } 76 | return config 77 | } 78 | 79 | // getEncoder 获取zapcore.Encoder 80 | func getEncoder() zapcore.Encoder { 81 | if global.GVA_CONFIG.Zap.Format == "json" { 82 | return zapcore.NewJSONEncoder(getEncoderConfig()) 83 | } 84 | return zapcore.NewConsoleEncoder(getEncoderConfig()) 85 | } 86 | 87 | // getEncoderCore 获取Encoder的zapcore.Core 88 | func getEncoderCore(fileName string, level zapcore.LevelEnabler) (core zapcore.Core) { 89 | writer := utils.GetWriteSyncer(fileName) // 使用file-rotatelogs进行日志分割 90 | return zapcore.NewCore(getEncoder(), writer, level) 91 | } 92 | 93 | // 自定义日志输出时间格式 94 | func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { 95 | enc.AppendString(t.Format(global.GVA_CONFIG.Zap.Prefix + "2006/01/02 - 15:04:05.000")) 96 | } 97 | -------------------------------------------------------------------------------- /global/global.go: -------------------------------------------------------------------------------- 1 | package global 2 | 3 | import ( 4 | "github.com/spf13/viper" 5 | "go.uber.org/zap" 6 | "gorm.io/gorm" 7 | "main.go/config" 8 | ) 9 | 10 | var ( 11 | GVA_DB *gorm.DB 12 | GVA_VP *viper.Viper 13 | GVA_LOG *zap.Logger 14 | GVA_CONFIG config.Server 15 | ) 16 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module main.go 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/fsnotify/fsnotify v1.5.1 // indirect 7 | github.com/fvbock/endless v0.0.0-20170109170031-447134032cb6 // indirect 8 | github.com/gin-contrib/sse v0.1.0 // indirect 9 | github.com/gin-gonic/gin v1.7.7 // indirect 10 | github.com/go-playground/locales v0.13.0 // indirect 11 | github.com/go-playground/universal-translator v0.17.0 // indirect 12 | github.com/go-playground/validator/v10 v10.4.1 // indirect 13 | github.com/go-sql-driver/mysql v1.6.0 // indirect 14 | github.com/golang/protobuf v1.5.2 // indirect 15 | github.com/hashicorp/hcl v1.0.0 // indirect 16 | github.com/jinzhu/copier v0.3.5 // indirect 17 | github.com/jinzhu/gorm v1.9.16 // indirect 18 | github.com/jinzhu/inflection v1.0.0 // indirect 19 | github.com/jinzhu/now v1.1.4 // indirect 20 | github.com/json-iterator/go v1.1.12 // indirect 21 | github.com/leodido/go-urn v1.2.0 // indirect 22 | github.com/magiconair/properties v1.8.5 // indirect 23 | github.com/mattn/go-isatty v0.0.14 // indirect 24 | github.com/mitchellh/mapstructure v1.4.3 // indirect 25 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 26 | github.com/modern-go/reflect2 v1.0.2 // indirect 27 | github.com/natefinch/lumberjack v2.0.0+incompatible // indirect 28 | github.com/pelletier/go-toml v1.9.4 // indirect 29 | github.com/spf13/afero v1.6.0 // indirect 30 | github.com/spf13/cast v1.4.1 // indirect 31 | github.com/spf13/jwalterweatherman v1.1.0 // indirect 32 | github.com/spf13/pflag v1.0.5 // indirect 33 | github.com/spf13/viper v1.10.1 // indirect 34 | github.com/subosito/gotenv v1.2.0 // indirect 35 | github.com/ugorji/go/codec v1.1.7 // indirect 36 | github.com/unrolled/secure v1.10.0 // indirect 37 | go.uber.org/atomic v1.7.0 // indirect 38 | go.uber.org/multierr v1.6.0 // indirect 39 | go.uber.org/zap v1.21.0 // indirect 40 | golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect 41 | golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect 42 | golang.org/x/text v0.3.7 // indirect 43 | google.golang.org/protobuf v1.27.1 // indirect 44 | gopkg.in/ini.v1 v1.66.2 // indirect 45 | gopkg.in/yaml.v2 v2.4.0 // indirect 46 | gorm.io/driver/mysql v1.3.2 // indirect 47 | gorm.io/gorm v1.23.3 // indirect 48 | ) 49 | -------------------------------------------------------------------------------- /initialize/gorm.go: -------------------------------------------------------------------------------- 1 | package initialize 2 | 3 | import ( 4 | "gorm.io/gorm" 5 | "main.go/global" 6 | ) 7 | 8 | // Gorm 初始化数据库并产生数据库全局变量 9 | // Author SliverHorn 10 | func Gorm() *gorm.DB { 11 | switch global.GVA_CONFIG.System.DbType { 12 | case "mysql": 13 | return GormMysql() 14 | default: 15 | return GormMysql() 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /initialize/gorm_mysql.go: -------------------------------------------------------------------------------- 1 | package initialize 2 | 3 | import ( 4 | "gorm.io/driver/mysql" 5 | "gorm.io/gorm" 6 | "main.go/global" 7 | "main.go/initialize/internal" 8 | ) 9 | 10 | func GormMysql() *gorm.DB { 11 | m := global.GVA_CONFIG.Mysql 12 | if m.Dbname == "" { 13 | return nil 14 | } 15 | mysqlConfig := mysql.Config{ 16 | DSN: m.Dsn(), // DSN data source name 17 | DefaultStringSize: 191, // string 类型字段的默认长度 18 | SkipInitializeWithVersion: false, // 根据版本自动配置 19 | } 20 | if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config()); err != nil { 21 | return nil 22 | } else { 23 | sqlDB, _ := db.DB() 24 | sqlDB.SetMaxIdleConns(m.MaxIdleConns) 25 | sqlDB.SetMaxOpenConns(m.MaxOpenConns) 26 | return db 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /initialize/internal/gorm.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "gorm.io/gorm" 5 | "gorm.io/gorm/logger" 6 | "log" 7 | "main.go/global" 8 | "os" 9 | "time" 10 | ) 11 | 12 | var Gorm = new(_gorm) 13 | 14 | type _gorm struct{} 15 | 16 | // Config gorm 自定义配置 17 | // Author [SliverHorn](https://github.com/SliverHorn) 18 | func (g *_gorm) Config() *gorm.Config { 19 | config := &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true} 20 | _default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{ 21 | SlowThreshold: 200 * time.Millisecond, 22 | LogLevel: logger.Warn, 23 | Colorful: true, 24 | }) 25 | switch global.GVA_CONFIG.Mysql.LogMode { 26 | case "silent", "Silent": 27 | config.Logger = _default.LogMode(logger.Silent) 28 | case "error", "Error": 29 | config.Logger = _default.LogMode(logger.Error) 30 | case "warn", "Warn": 31 | config.Logger = _default.LogMode(logger.Warn) 32 | case "info", "Info": 33 | config.Logger = _default.LogMode(logger.Info) 34 | default: 35 | config.Logger = _default.LogMode(logger.Info) 36 | } 37 | return config 38 | } 39 | -------------------------------------------------------------------------------- /initialize/internal/logger.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "fmt" 5 | "gorm.io/gorm/logger" 6 | "main.go/global" 7 | ) 8 | 9 | type writer struct { 10 | logger.Writer 11 | } 12 | 13 | // NewWriter writer 构造函数 14 | // Author [SliverHorn](https://github.com/SliverHorn) 15 | func NewWriter(w logger.Writer) *writer { 16 | return &writer{Writer: w} 17 | } 18 | 19 | // Printf 格式化打印日志 20 | // Author [SliverHorn](https://github.com/SliverHorn) 21 | func (w *writer) Printf(message string, data ...interface{}) { 22 | var logZap bool 23 | switch global.GVA_CONFIG.System.DbType { 24 | case "mysql": 25 | logZap = global.GVA_CONFIG.Mysql.LogZap 26 | } 27 | if logZap { 28 | global.GVA_LOG.Info(fmt.Sprintf(message+"\n", data...)) 29 | } else { 30 | w.Writer.Printf(message, data...) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /initialize/router.go: -------------------------------------------------------------------------------- 1 | package initialize 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "main.go/global" 6 | "main.go/middleware" 7 | "main.go/router" 8 | "net/http" 9 | ) 10 | 11 | func Routers() *gin.Engine { 12 | var Router = gin.Default() 13 | Router.StaticFS(global.GVA_CONFIG.Local.Path, http.Dir(global.GVA_CONFIG.Local.Path)) // 为用户头像和文件提供静态地址 14 | //Router.Use(middleware.LoadTls()) // 打开就能玩https了 15 | global.GVA_LOG.Info("use middleware logger") 16 | // 跨域 17 | Router.Use(middleware.Cors()) // 如需跨域可以打开 18 | global.GVA_LOG.Info("use middleware cors") 19 | // 方便统一添加路由组前缀 多服务器上线使用 20 | //商城后管路由 21 | manageRouter := router.RouterGroupApp.Manage 22 | ManageGroup := Router.Group("manage-api") 23 | PublicGroup := Router.Group("") 24 | 25 | { 26 | // 健康监测 27 | PublicGroup.GET("/health", func(c *gin.Context) { 28 | c.JSON(200, "ok") 29 | }) 30 | } 31 | { 32 | //商城后管路由初始化 33 | manageRouter.InitManageAdminUserRouter(ManageGroup) 34 | manageRouter.InitManageGoodsCategoryRouter(ManageGroup) 35 | manageRouter.InitManageGoodsInfoRouter(ManageGroup) 36 | manageRouter.InitManageCarouselRouter(ManageGroup) 37 | manageRouter.InitManageIndexConfigRouter(ManageGroup) 38 | manageRouter.InitManageOrderRouter(ManageGroup) 39 | } 40 | //商城前端路由 41 | mallRouter := router.RouterGroupApp.Mall 42 | MallGroup := Router.Group("api") 43 | { 44 | // 商城前端路由 45 | mallRouter.InitMallCarouselIndexRouter(MallGroup) 46 | mallRouter.InitMallGoodsInfoIndexRouter(MallGroup) 47 | mallRouter.InitMallGoodsCategoryIndexRouter(MallGroup) 48 | mallRouter.InitMallUserRouter(MallGroup) 49 | mallRouter.InitMallUserAddressRouter(MallGroup) 50 | mallRouter.InitMallShopCartRouter(MallGroup) 51 | mallRouter.InitMallOrderRouter(MallGroup) 52 | } 53 | global.GVA_LOG.Info("router register success") 54 | return Router 55 | } 56 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "main.go/core" 5 | "main.go/global" 6 | "main.go/initialize" 7 | ) 8 | 9 | func main() { 10 | 11 | global.GVA_VP = core.Viper() // 初始化Viper 12 | global.GVA_LOG = core.Zap() // 初始化zap日志库 13 | global.GVA_DB = initialize.Gorm() // gorm连接数据库 14 | 15 | core.RunWindowsServer() 16 | } 17 | -------------------------------------------------------------------------------- /middleware/cors.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "net/http" 6 | ) 7 | 8 | // 处理跨域请求,支持options访问 9 | func Cors() gin.HandlerFunc { 10 | return func(c *gin.Context) { 11 | method := c.Request.Method 12 | origin := c.Request.Header.Get("Origin") 13 | c.Header("Access-Control-Allow-Origin", origin) 14 | c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id,X-Requested-With") 15 | c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT") 16 | c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type") 17 | c.Header("Access-Control-Allow-Credentials", "true") 18 | 19 | // 放行所有OPTIONS方法 20 | if method == "OPTIONS" { 21 | c.AbortWithStatus(http.StatusNoContent) 22 | } 23 | // 处理请求 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /middleware/jwt.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "main.go/model/common/response" 6 | "main.go/service" 7 | "time" 8 | ) 9 | 10 | var manageAdminUserTokenService = service.ServiceGroupApp.ManageServiceGroup.ManageAdminUserTokenService 11 | var mallUserTokenService = service.ServiceGroupApp.MallServiceGroup.MallUserTokenService 12 | 13 | func AdminJWTAuth() gin.HandlerFunc { 14 | return func(c *gin.Context) { 15 | token := c.Request.Header.Get("token") 16 | if token == "" { 17 | response.FailWithDetailed(nil, "未登录或非法访问", c) 18 | c.Abort() 19 | return 20 | } 21 | err, mallAdminUserToken := manageAdminUserTokenService.ExistAdminToken(token) 22 | if err != nil { 23 | response.FailWithDetailed(nil, "未登录或非法访问", c) 24 | c.Abort() 25 | return 26 | } 27 | if time.Now().After(mallAdminUserToken.ExpireTime) { 28 | response.FailWithDetailed(nil, "授权已过期", c) 29 | manageAdminUserTokenService.DeleteMallAdminUserToken(token) 30 | c.Abort() 31 | return 32 | } 33 | c.Next() 34 | } 35 | 36 | } 37 | 38 | func UserJWTAuth() gin.HandlerFunc { 39 | return func(c *gin.Context) { 40 | token := c.Request.Header.Get("token") 41 | if token == "" { 42 | response.UnLogin(nil, c) 43 | c.Abort() 44 | return 45 | } 46 | err, mallUserToken := mallUserTokenService.ExistUserToken(token) 47 | if err != nil { 48 | response.UnLogin(nil, c) 49 | c.Abort() 50 | return 51 | } 52 | if time.Now().After(mallUserToken.ExpireTime) { 53 | response.FailWithDetailed(nil, "授权已过期", c) 54 | mallUserTokenService.DeleteMallUserToken(token) 55 | c.Abort() 56 | return 57 | } 58 | c.Next() 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /middleware/loadtls.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "fmt" 5 | "github.com/gin-gonic/gin" 6 | "github.com/unrolled/secure" 7 | ) 8 | 9 | func LoadTls() gin.HandlerFunc { 10 | return func(c *gin.Context) { 11 | middleware := secure.New(secure.Options{ 12 | SSLRedirect: true, 13 | SSLHost: "localhost:443", 14 | }) 15 | err := middleware.Process(c.Writer, c.Request) 16 | if err != nil { 17 | // 如果出现错误,请不要继续 18 | fmt.Println(err) 19 | return 20 | } 21 | // 继续往下处理 22 | c.Next() 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /model/common/enum/goods_category_enum.go: -------------------------------------------------------------------------------- 1 | package enum 2 | 3 | type GoodsCategoryLevel int8 4 | 5 | const ( 6 | Default GoodsCategoryLevel = 0 7 | LevelOne GoodsCategoryLevel = 1 8 | LevelTwo GoodsCategoryLevel = 2 9 | LevelThree GoodsCategoryLevel = 3 10 | ) 11 | 12 | func (g GoodsCategoryLevel) Info() (int, string) { 13 | switch g { 14 | case LevelOne: 15 | return 1, "一级分类" 16 | case LevelTwo: 17 | return 2, "二级分类" 18 | case LevelThree: 19 | return 3, "三级分类" 20 | default: 21 | return 0, "error" 22 | } 23 | } 24 | 25 | func (g GoodsCategoryLevel) Code() int { 26 | switch g { 27 | case LevelOne: 28 | return 1 29 | case LevelTwo: 30 | return 2 31 | case LevelThree: 32 | return 3 33 | default: 34 | return 0 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /model/common/enum/index_config_enum.go: -------------------------------------------------------------------------------- 1 | package enum 2 | 3 | type IndexConfigEnum int8 4 | 5 | // 首页配置项 1-搜索框热搜 2-搜索下拉框热搜 3-(首页)热销商品 4-(首页)新品上线 5-(首页)为你推荐 6 | const ( 7 | IndexSearchHots IndexConfigEnum = 1 8 | IndexSearchDownHots IndexConfigEnum = 2 9 | IndexGoodsHot IndexConfigEnum = 3 10 | IndexGoodsNew IndexConfigEnum = 4 11 | IndexGoodsRecommond IndexConfigEnum = 5 12 | ) 13 | 14 | func (i IndexConfigEnum) Info() (int, string) { 15 | switch i { 16 | case IndexSearchHots: 17 | return 1, "INDEX_SEARCH_HOTS" 18 | case IndexSearchDownHots: 19 | return 2, "二级分类" 20 | case IndexGoodsHot: 21 | return 3, "三级分类" 22 | case IndexGoodsNew: 23 | return 4, "三级分类" 24 | case IndexGoodsRecommond: 25 | return 5, "三级分类" 26 | default: 27 | return 0, "DEFAULT" 28 | } 29 | } 30 | 31 | func (i IndexConfigEnum) Code() int { 32 | switch i { 33 | case IndexSearchHots: 34 | return 1 35 | case IndexSearchDownHots: 36 | return 2 37 | case IndexGoodsHot: 38 | return 3 39 | case IndexGoodsNew: 40 | return 4 41 | case IndexGoodsRecommond: 42 | return 5 43 | default: 44 | return 0 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /model/common/enum/mall_order_status.go: -------------------------------------------------------------------------------- 1 | package enum 2 | 3 | type MallOrderStatusEnum int 4 | 5 | const ( 6 | DEFAULT MallOrderStatusEnum = -9 7 | ORDER_PRE_PAY MallOrderStatusEnum = 0 8 | ORDER_PAID MallOrderStatusEnum = 1 9 | ORDER_PACKAGED MallOrderStatusEnum = 2 10 | ORDER_EXPRESS MallOrderStatusEnum = 3 11 | ORDER_SUCCESS MallOrderStatusEnum = 4 12 | ORDER_CLOSED_BY_MALLUSER MallOrderStatusEnum = -1 13 | ORDER_CLOSED_BY_EXPIRED MallOrderStatusEnum = -2 14 | ORDER_CLOSED_BY_JUDGE MallOrderStatusEnum = -3 15 | ) 16 | 17 | func GetNewBeeMallOrderStatusEnumByStatus(status int) (int, string) { 18 | switch status { 19 | case 0: 20 | return 0, "待支付" 21 | case 1: 22 | return 1, "已支付" 23 | case 2: 24 | return 2, "配货完成" 25 | case 3: 26 | return 3, "出库成功" 27 | case 4: 28 | return 4, "交易成功" 29 | case -1: 30 | return -1, "手动关闭" 31 | case -2: 32 | return -2, "超时关闭" 33 | case -3: 34 | return -3, "商家关闭" 35 | default: 36 | return -9, "error" 37 | } 38 | } 39 | 40 | func (g MallOrderStatusEnum) Code() int { 41 | switch g { 42 | case ORDER_PRE_PAY: 43 | return 0 44 | case ORDER_PAID: 45 | return 1 46 | case ORDER_PACKAGED: 47 | return 2 48 | case ORDER_EXPRESS: 49 | return 3 50 | case ORDER_SUCCESS: 51 | return 4 52 | case ORDER_CLOSED_BY_MALLUSER: 53 | return -1 54 | case ORDER_CLOSED_BY_EXPIRED: 55 | return -2 56 | case ORDER_CLOSED_BY_JUDGE: 57 | return 3 58 | default: 59 | return -9 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /model/common/json_time.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "database/sql/driver" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | // JSONTime format json time field by myself 10 | type JSONTime struct { 11 | time.Time 12 | } 13 | 14 | // MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S 15 | func (t JSONTime) MarshalJSON() ([]byte, error) { 16 | formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05")) 17 | return []byte(formatted), nil 18 | } 19 | 20 | // Value insert timestamp into mysql need this function. 21 | func (t JSONTime) Value() (driver.Value, error) { 22 | var zeroTime time.Time 23 | if t.Time.UnixNano() == zeroTime.UnixNano() { 24 | return nil, nil 25 | } 26 | return t.Time, nil 27 | } 28 | 29 | // Scan valueof time.Time 30 | func (t *JSONTime) Scan(v interface{}) error { 31 | value, ok := v.(time.Time) 32 | if ok { 33 | *t = JSONTime{Time: value} 34 | return nil 35 | } 36 | return fmt.Errorf("can not convert %v to timestamp", v) 37 | } 38 | -------------------------------------------------------------------------------- /model/common/request/common.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | // PageInfo Paging common input parameter structure 4 | type PageInfo struct { 5 | PageNumber int `json:"pageNumber" form:"pageNumber"` // 页码 6 | PageSize int `json:"pageSize" form:"pageSize"` // 每页大小 7 | } 8 | 9 | // GetById Find by id structure 10 | type GetById struct { 11 | ID float64 `json:"id" form:"id"` // 主键ID 12 | } 13 | 14 | func (r *GetById) Uint() uint { 15 | return uint(r.ID) 16 | } 17 | 18 | type IdsReq struct { 19 | Ids []int `json:"ids" form:"ids"` 20 | } 21 | 22 | // GetAuthorityId Get role by id structure 23 | type GetAuthorityId struct { 24 | AuthorityId string `json:"authorityId" form:"authorityId"` // 角色ID 25 | } 26 | 27 | type Empty struct{} 28 | -------------------------------------------------------------------------------- /model/common/response/common.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | type PageResult struct { 4 | List interface{} `json:"list"` 5 | TotalCount int64 `json:"totalCount"` 6 | TotalPage int `json:"totalPage"` 7 | CurrPage int `json:"currPage"` 8 | PageSize int `json:"pageSize"` 9 | } 10 | -------------------------------------------------------------------------------- /model/common/response/response.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "net/http" 6 | ) 7 | 8 | type Response struct { 9 | ResultCode int `json:"resultCode"` 10 | Data interface{} `json:"data"` 11 | Msg string `json:"message"` 12 | } 13 | 14 | const ( 15 | ERROR = 500 16 | SUCCESS = 200 17 | UNLOGIN = 416 18 | ) 19 | 20 | func Result(code int, data interface{}, msg string, c *gin.Context) { 21 | // 开始时间 22 | c.JSON(http.StatusOK, Response{ 23 | code, 24 | data, 25 | msg, 26 | }) 27 | } 28 | 29 | func Ok(c *gin.Context) { 30 | Result(SUCCESS, map[string]interface{}{}, "操作成功", c) 31 | } 32 | 33 | func OkWithMessage(message string, c *gin.Context) { 34 | Result(SUCCESS, map[string]interface{}{}, message, c) 35 | } 36 | 37 | func OkWithData(data interface{}, c *gin.Context) { 38 | Result(SUCCESS, data, "SUCCESS", c) 39 | } 40 | 41 | func OkWithDetailed(data interface{}, message string, c *gin.Context) { 42 | Result(SUCCESS, data, message, c) 43 | } 44 | 45 | func Fail(c *gin.Context) { 46 | Result(ERROR, map[string]interface{}{}, "操作失败", c) 47 | } 48 | 49 | func FailWithMessage(message string, c *gin.Context) { 50 | Result(ERROR, map[string]interface{}{}, message, c) 51 | } 52 | 53 | func FailWithDetailed(data interface{}, message string, c *gin.Context) { 54 | Result(ERROR, data, message, c) 55 | } 56 | 57 | func UnLogin(data interface{}, c *gin.Context) { 58 | Result(UNLOGIN, data, "未登录!", c) 59 | } 60 | -------------------------------------------------------------------------------- /model/example/exa_breakpoint_continue.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | // file struct, 文件结构体 8 | type ExaFile struct { 9 | ID int 10 | FileName string 11 | FileMd5 string 12 | FilePath string 13 | ExaFileChunk []ExaFileChunk 14 | ChunkTotal int 15 | IsFinish bool 16 | CreateTime common.JSONTime 17 | UpdateTime common.JSONTime 18 | } 19 | 20 | // file chunk struct, 切片结构体 21 | type ExaFileChunk struct { 22 | ID int 23 | ExaFileID uint 24 | FileChunkNumber int 25 | FileChunkPath string 26 | CreateTime common.JSONTime 27 | UpdateTime common.JSONTime 28 | } 29 | -------------------------------------------------------------------------------- /model/example/exa_file_upload_download.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import "main.go/model/common" 4 | 5 | type ExaFileUploadAndDownload struct { 6 | ID int `gorm:"primarykey"` // 主键ID 7 | Name string `json:"name" gorm:"comment:文件名"` // 文件名 8 | Url string `json:"url" gorm:"comment:文件地址"` // 文件地址 9 | Tag string `json:"tag" gorm:"comment:文件标签"` // 文件标签 10 | Key string `json:"key" gorm:"comment:编号"` // 编号 11 | CreateTime common.JSONTime `json:"createTime" gorm:"column:create_time;comment:创建时间;type:datetime"` // 创建时间 12 | UpdateTime common.JSONTime `json:"updateTime" gorm:"column:update_time;comment:修改时间;type:datetime"` // 更新时间 13 | } 14 | -------------------------------------------------------------------------------- /model/example/response/exa_breakpoint_continue.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | import "main.go/model/example" 4 | 5 | type FilePathResponse struct { 6 | FilePath string `json:"filePath"` 7 | } 8 | 9 | type FileResponse struct { 10 | File example.ExaFile `json:"file"` 11 | } 12 | -------------------------------------------------------------------------------- /model/example/response/exa_file_upload_download.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | import "main.go/model/example" 4 | 5 | type ExaFileResponse struct { 6 | File example.ExaFileUploadAndDownload `json:"file"` 7 | } 8 | -------------------------------------------------------------------------------- /model/mall/mall_order_address.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | type MallOrderAddress struct { 4 | OrderId int `json:"orderId"` 5 | 6 | UserName string `json:"userName"` 7 | 8 | UserPhone string `json:"userPhone"` 9 | 10 | ProvinceName string `json:"provinceName"` 11 | 12 | CityName string `json:"cityName"` 13 | 14 | RegionName string `json:"regionName"` 15 | 16 | DetailAddress string `json:"detailAddress"` 17 | } 18 | -------------------------------------------------------------------------------- /model/mall/mall_shop_cart_item.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | // MallShoppingCartItem 结构体 8 | // 如果含有time.Time 请自行import time包 9 | type MallShoppingCartItem struct { 10 | CartItemId int `json:"cartItemId" form:"cartItemId" gorm:"primarykey;AUTO_INCREMENT"` 11 | UserId int `json:"userId" form:"userId" gorm:"column:user_id;comment:用户主键id;type:bigint"` 12 | GoodsId int `json:"goodsId" form:"goodsId" gorm:"column:goods_id;comment:关联商品id;type:bigint"` 13 | GoodsCount int `json:"goodsCount" form:"goodsCount" gorm:"column:goods_count;comment:数量(最大为5);type:int"` 14 | IsDeleted int `json:"isDeleted" form:"isDeleted" gorm:"column:is_deleted;comment:删除标识字段(0-未删除 1-已删除);type:tinyint"` 15 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:创建时间;type:datetime"` 16 | UpdateTime common.JSONTime `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:最新修改时间;type:datetime"` 17 | } 18 | 19 | // TableName MallShoppingCartItem 表名 20 | func (MallShoppingCartItem) TableName() string { 21 | return "tb_newbee_mall_shopping_cart_item" 22 | } 23 | -------------------------------------------------------------------------------- /model/mall/mall_user.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | type MallUser struct { 8 | UserId int `json:"userId" form:"userId" gorm:"primarykey;AUTO_INCREMENT"` 9 | NickName string `json:"nickName" form:"nickName" gorm:"column:nick_name;comment:用户昵称;type:varchar(50);"` 10 | LoginName string `json:"loginName" form:"loginName" gorm:"column:login_name;comment:登陆名称(默认为手机号);type:varchar(11);"` 11 | PasswordMd5 string `json:"passwordMd5" form:"passwordMd5" gorm:"column:password_md5;comment:MD5加密后的密码;type:varchar(32);"` 12 | IntroduceSign string `json:"introduceSign" form:"introduceSign" gorm:"column:introduce_sign;comment:个性签名;type:varchar(100);"` 13 | IsDeleted int `json:"isDeleted" form:"isDeleted" gorm:"column:is_deleted;comment:注销标识字段(0-正常 1-已注销);type:tinyint"` 14 | LockedFlag int `json:"lockedFlag" form:"lockedFlag" gorm:"column:locked_flag;comment:锁定标识字段(0-未锁定 1-已锁定);type:tinyint"` 15 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:注册时间;type:datetime"` 16 | } 17 | 18 | // TableName MallUser 表名 19 | func (MallUser) TableName() string { 20 | return "tb_newbee_mall_user" 21 | } 22 | -------------------------------------------------------------------------------- /model/mall/mall_user_address.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | // MallUserAddress 结构体 8 | // 如果含有time.Time 请自行import time包 9 | type MallUserAddress struct { 10 | AddressId int `json:"addressId" form:"addressId" gorm:"primarykey;AUTO_INCREMENT"` 11 | UserId int `json:"userId" form:"userId" gorm:"column:user_id;comment:用户主键id;type:bigint"` 12 | UserName string `json:"userName" form:"userName" gorm:"column:user_name;comment:收货人姓名;type:varchar(30);"` 13 | UserPhone string `json:"userPhone" form:"userPhone" gorm:"column:user_phone;comment:收货人手机号;type:varchar(11);"` 14 | DefaultFlag int `json:"defaultFlag" form:"defaultFlag" gorm:"column:default_flag;comment:是否为默认 0-非默认 1-是默认;type:tinyint"` 15 | ProvinceName string `json:"provinceName" form:"provinceName" gorm:"column:province_name;comment:省;type:varchar(32);"` 16 | CityName string `json:"cityName" form:"cityName" gorm:"column:city_name;comment:城;type:varchar(32);"` 17 | RegionName string `json:"regionName" form:"regionName" gorm:"column:region_name;comment:区;type:varchar(32);"` 18 | DetailAddress string `json:"detailAddress" form:"detailAddress" gorm:"column:detail_address;comment:收件详细地址(街道/楼宇/单元);type:varchar(64);"` 19 | IsDeleted int `json:"isDeleted" form:"isDeleted" gorm:"column:is_deleted;comment:删除标识字段(0-未删除 1-已删除);type:tinyint"` 20 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:添加时间;type:datetime"` 21 | UpdateTime common.JSONTime `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:修改时间;type:datetime"` 22 | } 23 | 24 | // TableName MallUserAddress 表名 25 | func (MallUserAddress) TableName() string { 26 | return "tb_newbee_mall_user_address" 27 | } 28 | -------------------------------------------------------------------------------- /model/mall/mall_user_token.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | // MallUserToken 结构体 8 | // 如果含有time.Time 请自行import time包 9 | type MallUserToken struct { 10 | UserId int `json:"userId" form:"userId" gorm:"primarykey;AUTO_INCREMENT"` 11 | Token string `json:"token" form:"token" gorm:"column:token;comment:token值(32位字符串);type:varchar(32);"` 12 | UpdateTime time.Time `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:修改时间;type:datetime"` 13 | ExpireTime time.Time `json:"expireTime" form:"expireTime" gorm:"column:expire_time;comment:token过期时间;type:datetime"` 14 | } 15 | 16 | // TableName MallUserToken 表名 17 | func (MallUserToken) TableName() string { 18 | return "tb_newbee_mall_user_token" 19 | } 20 | -------------------------------------------------------------------------------- /model/mall/request/mall_goods_info.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | type GoodsSearchParams struct { 4 | Keyword string `form:"keyword"` 5 | GoodsCategoryId int `form:"goodsCategoryId"` 6 | OrderBy string `form:"orderBy"` 7 | PageNumber int `form:"pageNumber"` 8 | } 9 | -------------------------------------------------------------------------------- /model/mall/request/mall_order.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | type PaySuccessParams struct { 4 | OrderNo string `json:"orderNo"` 5 | PayType int `json:"payType"` 6 | } 7 | 8 | type OrderSearchParams struct { 9 | Status string `form:"status"` 10 | PageNumber int `form:"pageNumber"` 11 | } 12 | 13 | type SaveOrderParam struct { 14 | CartItemIds []int `json:"cartItemIds"` 15 | AddressId int `json:"addressId"` 16 | } 17 | -------------------------------------------------------------------------------- /model/mall/request/mall_shop_cart.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "main.go/model/common/request" 5 | ) 6 | 7 | type MallShopCartSearch struct { 8 | request.PageInfo 9 | } 10 | 11 | type SaveCartItemParam struct { 12 | GoodsCount int `json:"goodsCount"` 13 | GoodsId int `json:"goodsId"` 14 | } 15 | 16 | type UpdateCartItemParam struct { 17 | CartItemId int `json:"cartItemId"` 18 | GoodsCount int `json:"goodsCount"` 19 | } 20 | -------------------------------------------------------------------------------- /model/mall/request/mall_user.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | //用户注册 4 | type RegisterUserParam struct { 5 | LoginName string `json:"loginName"` 6 | Password string `json:"password"` 7 | } 8 | 9 | //更新用户信息 10 | type UpdateUserInfoParam struct { 11 | NickName string `json:"nickName"` 12 | PasswordMd5 string `json:"passwordMd5"` 13 | IntroduceSign string `json:"introduceSign"` 14 | } 15 | 16 | type UserLoginParam struct { 17 | LoginName string `json:"loginName"` 18 | PasswordMd5 string `json:"passwordMd5"` 19 | } 20 | -------------------------------------------------------------------------------- /model/mall/request/mall_user_address.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | type AddAddressParam struct { 4 | UserName string `json:"userName"` 5 | 6 | UserPhone string `json:"userPhone"` 7 | 8 | DefaultFlag byte `json:"defaultFlag"` // 0-不是 1-是 9 | 10 | ProvinceName string `json:"provinceName"` 11 | CityName string `json:"cityName"` 12 | RegionName string `json:"regionName"` 13 | DetailAddress string `json:"detailAddress"` 14 | } 15 | 16 | type UpdateAddressParam struct { 17 | AddressId string `json:"addressId"` 18 | UserId int `json:"userId"` 19 | UserName string `json:"userName"` 20 | UserPhone string `json:"userPhone"` 21 | DefaultFlag byte `json:"defaultFlag"` // 0-不是 1-是 22 | ProvinceName string `json:"provinceName"` 23 | CityName string `json:"cityName"` 24 | RegionName string `json:"regionName"` 25 | DetailAddress string `json:"detailAddress"` 26 | } 27 | -------------------------------------------------------------------------------- /model/mall/response/mall_carousel.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | type MallCarouselIndexResponse struct { 4 | CarouselUrl string `json:"carouselUrl"` 5 | RedirectUrl string `json:"redirectUrl"` 6 | } 7 | -------------------------------------------------------------------------------- /model/mall/response/mall_goods_category.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | //首页分类数据VO(第三级) 4 | type ThirdLevelCategoryVO struct { 5 | CategoryId int `json:"categoryId"` 6 | CategoryLevel int `json:"categoryLevel"` 7 | CategoryName string `json:"categoryName" ` 8 | } 9 | 10 | type SecondLevelCategoryVO struct { 11 | CategoryId int `json:"categoryId"` 12 | ParentId int `json:"parentId"` 13 | CategoryLevel int `json:"categoryLevel"` 14 | CategoryName string `json:"categoryName" ` 15 | ThirdLevelCategoryVOS []ThirdLevelCategoryVO `json:"thirdLevelCategoryVOS"` 16 | } 17 | 18 | type NewBeeMallIndexCategoryVO struct { 19 | CategoryId int `json:"categoryId"` 20 | //ParentId int `json:"parentId"` 21 | CategoryLevel int `json:"categoryLevel"` 22 | CategoryName string `json:"categoryName" ` 23 | SecondLevelCategoryVOS []SecondLevelCategoryVO `json:"secondLevelCategoryVOS"` 24 | } 25 | -------------------------------------------------------------------------------- /model/mall/response/mall_goods_info.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | type GoodsSearchResponse struct { 4 | GoodsId int `json:"goodsId"` 5 | GoodsName string `json:"goodsName"` 6 | GoodsIntro string `json:"goodsIntro"` 7 | GoodsCoverImg string `json:"goodsCoverImg"` 8 | SellingPrice int `json:"sellingPrice"` 9 | } 10 | 11 | type GoodsInfoDetailResponse struct { 12 | GoodsId int `json:"goodsId"` 13 | GoodsName string `json:"goodsName"` 14 | GoodsIntro string `json:"goodsIntro"` 15 | GoodsCoverImg string `json:"goodsCoverImg"` 16 | SellingPrice int `json:"sellingPrice"` 17 | GoodsDetailContent string `json:"goodsDetailContent" ` 18 | OriginalPrice int `json:"originalPrice" ` 19 | Tag string `json:"tag" form:"tag" ` 20 | GoodsCarouselList []string `json:"goodsCarouselList" ` 21 | } 22 | -------------------------------------------------------------------------------- /model/mall/response/mall_index_config.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | type MallIndexConfigGoodsResponse struct { 4 | GoodsId int `json:"goodsId"` 5 | GoodsName string `json:"goodsName"` 6 | GoodsIntro string `json:"goodsIntro"` 7 | GoodsCoverImg string `json:"goodsCoverImg"` 8 | SellingPrice int `json:"sellingPrice"` 9 | Tag string `json:"tag"` 10 | } 11 | -------------------------------------------------------------------------------- /model/mall/response/mall_order.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | import "main.go/model/common" 4 | 5 | type MallOrderResponse struct { 6 | OrderId int `json:"orderId"` 7 | OrderNo string `json:"orderNo"` 8 | TotalPrice int `json:"totalPrice"` 9 | PayType int `json:"payType"` 10 | OrderStatus int `json:"orderStatus"` 11 | OrderStatusString string `json:"orderStatusString"` 12 | CreateTime common.JSONTime `json:"createTime"` 13 | NewBeeMallOrderItemVOS []NewBeeMallOrderItemVO `json:"newBeeMallOrderItemVOS"` 14 | } 15 | 16 | type NewBeeMallOrderItemVO struct { 17 | GoodsId int `json:"goodsId"` 18 | GoodsName string `json:"goodsName"` 19 | GoodsCount int `json:"goodsCount"` 20 | GoodsCoverImg string `json:"goodsCoverImg"` 21 | SellingPrice int `json:"sellingPrice"` 22 | } 23 | 24 | type MallOrderDetailVO struct { 25 | OrderNo string `json:"orderNo"` 26 | TotalPrice int `json:"totalPrice"` 27 | PayStatus int `json:"payStatus"` 28 | PayType int `json:"payType"` 29 | PayTypeString string `json:"payTypeString"` 30 | PayTime common.JSONTime `json:"payTime"` 31 | OrderStatus int `json:"orderStatus"` 32 | OrderStatusString string `json:"orderStatusString"` 33 | CreateTime common.JSONTime `json:"createTime"` 34 | NewBeeMallOrderItemVOS []NewBeeMallOrderItemVO `json:"newBeeMallOrderItemVOS"` 35 | } 36 | -------------------------------------------------------------------------------- /model/mall/response/mall_shop_cart.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | type CartItemResponse struct { 4 | CartItemId int `json:"cartItemId"` 5 | 6 | GoodsId int `json:"goodsId"` 7 | 8 | GoodsCount int `json:"goodsCount"` 9 | 10 | GoodsName string `json:"goodsName"` 11 | 12 | GoodsCoverImg string `json:"goodsCoverImg"` 13 | 14 | SellingPrice int `json:"sellingPrice"` 15 | } 16 | -------------------------------------------------------------------------------- /model/mall/response/mall_user.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | type MallUserDetailResponse struct { 4 | NickName string `json:"nickName"` 5 | LoginName string `json:"loginName"` 6 | IntroduceSign string `json:"introduceSign"` 7 | } 8 | -------------------------------------------------------------------------------- /model/manage/manage_admin_user.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | // MallAdminUser 结构体 4 | type MallAdminUser struct { 5 | AdminUserId int `json:"adminUserId" form:"adminUserId" gorm:"primarykey;AUTO_INCREMENT"` 6 | LoginUserName string `json:"loginUserName" form:"loginUserName" gorm:"column:login_user_name;comment:管理员登陆名称;type:varchar(50);"` 7 | LoginPassword string `json:"loginPassword" form:"loginPassword" gorm:"column:login_password;comment:管理员登陆密码;type:varchar(50);"` 8 | NickName string `json:"nickName" form:"nickName" gorm:"column:nick_name;comment:管理员显示昵称;type:varchar(50);"` 9 | Locked int `json:"locked" form:"locked" gorm:"column:locked;comment:是否锁定 0未锁定 1已锁定无法登陆;type:tinyint"` 10 | } 11 | 12 | func (MallAdminUser) TableName() string { 13 | return "tb_newbee_mall_admin_user" 14 | } 15 | -------------------------------------------------------------------------------- /model/manage/manage_admin_user_token.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import "time" 4 | 5 | // MallAdminUserToken 管理员登录态 6 | type MallAdminUserToken struct { 7 | AdminUserId int `json:"adminUserId" form:"adminUserId" gorm:"primarykey;AUTO_INCREMENT"` 8 | Token string `json:"token" form:"token" gorm:"column:token;comment:token值(32位字符串);type:varchar(32);"` 9 | UpdateTime time.Time `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:修改时间;type:datetime"` 10 | ExpireTime time.Time `json:"expireTime" form:"expireTime" gorm:"column:expire_time;comment:token过期时间;type:datetime"` 11 | } 12 | 13 | func (MallAdminUserToken) TableName() string { 14 | return "tb_newbee_mall_admin_user_token" 15 | } 16 | -------------------------------------------------------------------------------- /model/manage/manage_carousel.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | // 轮播图 8 | type MallCarousel struct { 9 | CarouselId int `json:"carouselId" form:"carouselId" gorm:"primarykey;AUTO_INCREMENT"` 10 | CarouselUrl string `json:"carouselUrl" form:"carouselUrl" gorm:"column:carousel_url;comment:轮播图;type:varchar(100);"` 11 | RedirectUrl string `json:"redirectUrl" form:"redirectUrl" gorm:"column:redirect_url;comment:点击后的跳转地址(默认不跳转);type:varchar(100);"` 12 | CarouselRank int `json:"carouselRank" form:"carouselRank" gorm:"column:carousel_rank;comment:排序值(字段越大越靠前);type:int"` 13 | IsDeleted int `json:"isDeleted" form:"isDeleted" gorm:"column:is_deleted;comment:删除标识字段(0-未删除 1-已删除);type:tinyint"` 14 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:创建时间;type:datetime"` 15 | CreateUser int `json:"createUser" form:"createUser" gorm:"column:create_user;comment:创建者id;type:int"` 16 | UpdateTime common.JSONTime `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:修改时间;type:datetime"` 17 | UpdateUser int `json:"updateUser" form:"updateUser" gorm:"column:update_user;comment:修改者id;type:int"` 18 | } 19 | 20 | // TableName MallCarousel 表名 21 | func (MallCarousel) TableName() string { 22 | return "tb_newbee_mall_carousel" 23 | } 24 | -------------------------------------------------------------------------------- /model/manage/manage_goods_category.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | type MallGoodsCategory struct { 8 | CategoryId int `json:"categoryId"gorm:"primarykey;AUTO_INCREMENT"` 9 | CategoryLevel int `json:"categoryLevel" gorm:"comment:分类等级"` 10 | ParentId int `json:"parentId" gorm:"comment:父类id"` 11 | CategoryName string `json:"categoryName" gorm:"comment:分类名称"` 12 | CategoryRank int `json:"categoryRank" gorm:"comment:排序比重"` 13 | IsDeleted int `json:"isDeleted" gorm:"comment:是否删除"` 14 | CreateTime common.JSONTime `json:"createTime" gorm:"column:create_time;comment:创建时间;type:datetime"` // 创建时间 15 | UpdateTime common.JSONTime `json:"updateTime" gorm:"column:update_time;comment:修改时间;type:datetime"` // 更新时间 16 | } 17 | 18 | func (MallGoodsCategory) TableName() string { 19 | return "tb_newbee_mall_goods_category" 20 | } 21 | -------------------------------------------------------------------------------- /model/manage/manage_goods_info.go: -------------------------------------------------------------------------------- 1 | // 自动生成模板MallGoodsInfo 2 | package manage 3 | 4 | import ( 5 | "main.go/model/common" 6 | ) 7 | 8 | // MallGoodsInfo 结构体 9 | // 如果含有time.Time 请自行import time包 10 | type MallGoodsInfo struct { 11 | GoodsId int `json:"goodsId" form:"goodsId" gorm:"primarykey;AUTO_INCREMENT"` 12 | GoodsName string `json:"goodsName" form:"goodsName" gorm:"column:goods_name;comment:商品名;type:varchar(200);"` 13 | GoodsIntro string `json:"goodsIntro" form:"goodsIntro" gorm:"column:goods_intro;comment:商品简介;type:varchar(200);"` 14 | GoodsCategoryId int `json:"goodsCategoryId" form:"goodsCategoryId" gorm:"column:goods_category_id;comment:关联分类id;type:bigint"` 15 | GoodsCoverImg string `json:"goodsCoverImg" form:"goodsCoverImg" gorm:"column:goods_cover_img;comment:商品主图;type:varchar(200);"` 16 | GoodsCarousel string `json:"goodsCarousel" form:"goodsCarousel" gorm:"column:goods_carousel;comment:商品轮播图;type:varchar(500);"` 17 | GoodsDetailContent string `json:"goodsDetailContent" form:"goodsDetailContent" gorm:"column:goods_detail_content;comment:商品详情;type:text;"` 18 | OriginalPrice int `json:"originalPrice" form:"originalPrice" gorm:"column:original_price;comment:商品价格;type:int"` 19 | SellingPrice int `json:"sellingPrice" form:"sellingPrice" gorm:"column:selling_price;comment:商品实际售价;type:int"` 20 | StockNum int `json:"stockNum" form:"stockNum" gorm:"column:stock_num;comment:商品库存数量;type:int"` 21 | Tag string `json:"tag" form:"tag" gorm:"column:tag;comment:商品标签;type:varchar(20);"` 22 | GoodsSellStatus int `json:"goodsSellStatus" form:"goodsSellStatus" gorm:"column:goods_sell_status;comment:商品上架状态 1-下架 0-上架;type:tinyint"` 23 | CreateUser int `json:"createUser" form:"createUser" gorm:"column:create_user;comment:添加者主键id;type:int"` 24 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:商品添加时间;type:datetime"` 25 | UpdateUser int `json:"updateUser" form:"updateUser" gorm:"column:update_user;comment:修改者主键id;type:int"` 26 | UpdateTime common.JSONTime `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:商品修改时间;type:datetime"` 27 | } 28 | 29 | // TableName MallGoodsInfo 表名 30 | func (MallGoodsInfo) TableName() string { 31 | return "tb_newbee_mall_goods_info" 32 | } 33 | -------------------------------------------------------------------------------- /model/manage/manage_index_config.go: -------------------------------------------------------------------------------- 1 | // 自动生成模板MallIndexConfig 2 | package manage 3 | 4 | import ( 5 | "main.go/model/common" 6 | ) 7 | 8 | // MallIndexConfig 结构体 9 | // 如果含有time.Time 请自行import time包 10 | type MallIndexConfig struct { 11 | ConfigId int `json:"configId" form:"configId" gorm:"primarykey;AUTO_INCREMENT"` 12 | ConfigName string `json:"configName" form:"configName" gorm:"column:config_name;comment:显示字符(配置搜索时不可为空,其他可为空);type:varchar(50);"` 13 | ConfigType int `json:"configType" form:"configType" gorm:"column:config_type;comment:1-搜索框热搜 2-搜索下拉框热搜 3-(首页)热销商品 4-(首页)新品上线 5-(首页)为你推荐;type:tinyint"` 14 | GoodsId int `json:"goodsId" form:"goodsId" gorm:"column:goods_id;comment:商品id 默认为0;type:bigint"` 15 | RedirectUrl string `json:"redirectUrl" form:"redirectUrl" gorm:"column:redirect_url;comment:点击后的跳转地址(默认不跳转);type:varchar(100);"` 16 | ConfigRank int `json:"configRank" form:"configRank" gorm:"column:config_rank;comment:排序值(字段越大越靠前);type:int"` 17 | IsDeleted int `json:"isDeleted" form:"isDeleted" gorm:"column:is_deleted;comment:删除标识字段(0-未删除 1-已删除);type:tinyint"` 18 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:创建时间;type:datetime"` 19 | CreateUser int `json:"createUser" form:"createUser" gorm:"column:create_user;comment:创建者id;type:int"` 20 | UpdateTime common.JSONTime `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:最新修改时间;type:datetime"` 21 | UpdateUser int `json:"updateUser" form:"updateUser" gorm:"column:update_user;comment:修改者id;type:int"` 22 | } 23 | 24 | // TableName MallIndexConfig 表名 25 | func (MallIndexConfig) TableName() string { 26 | return "tb_newbee_mall_index_config" 27 | } 28 | -------------------------------------------------------------------------------- /model/manage/manage_order.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | type MallOrder struct { 8 | OrderId int `json:"orderId" form:"orderId" gorm:"primarykey;AUTO_INCREMENT"` 9 | OrderNo string `json:"orderNo" form:"orderNo" gorm:"column:order_no;comment:订单号;type:varchar(20);"` 10 | UserId int `json:"userId" form:"userId" gorm:"column:user_id;comment:用户主键id;type:bigint"` 11 | TotalPrice int `json:"totalPrice" form:"totalPrice" gorm:"column:total_price;comment:订单总价;type:int"` 12 | PayStatus int `json:"payStatus" form:"payStatus" gorm:"column:pay_status;comment:支付状态:0.未支付,1.支付成功,-1:支付失败;type:tinyint"` 13 | PayType int `json:"payType" form:"payType" gorm:"column:pay_type;comment:0.无 1.支付宝支付 2.微信支付;type:tinyint"` 14 | PayTime common.JSONTime `json:"payTime" form:"payTime" gorm:"column:pay_time;comment:支付时间;type:datetime"` 15 | OrderStatus int `json:"orderStatus" form:"orderStatus" gorm:"column:order_status;comment:订单状态:0.待支付 1.已支付 2.配货完成 3:出库成功 4.交易成功 -1.手动关闭 -2.超时关闭 -3.商家关闭;type:tinyint"` 16 | ExtraInfo string `json:"extraInfo" form:"extraInfo" gorm:"column:extra_info;comment:订单body;type:varchar(100);"` 17 | IsDeleted int `json:"isDeleted" form:"isDeleted" gorm:"column:is_deleted;comment:删除标识字段(0-未删除 1-已删除);type:tinyint"` 18 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:创建时间;type:datetime"` 19 | UpdateTime common.JSONTime `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:最新修改时间;type:datetime"` 20 | } 21 | 22 | // TableName MallOrder 表名 23 | func (MallOrder) TableName() string { 24 | return "tb_newbee_mall_order" 25 | } 26 | -------------------------------------------------------------------------------- /model/manage/manage_order_item.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import "main.go/model/common" 4 | 5 | type MallOrderItem struct { 6 | OrderItemId int `json:"orderItemId" gorm:"primarykey;AUTO_INCREMENT"` 7 | OrderId int `json:"orderId" form:"orderId" gorm:"column:order_id;;type:bigint"` 8 | GoodsId int `json:"goodsId" form:"goodsId" gorm:"column:goods_id;;type:bigint"` 9 | GoodsName string `json:"goodsName" form:"goodsName" gorm:"column:goods_name;comment:商品名;type:varchar(200);"` 10 | GoodsCoverImg string `json:"goodsCoverImg" form:"goodsCoverImg" gorm:"column:goods_cover_img;comment:商品主图;type:varchar(200);"` 11 | SellingPrice int `json:"sellingPrice" form:"sellingPrice" gorm:"column:selling_price;comment:商品实际售价;type:int"` 12 | GoodsCount int `json:"goodsCount" form:"goodsCount" gorm:"column:goods_count;;type:bigint"` 13 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:创建时间;type:datetime"` 14 | } 15 | 16 | func (MallOrderItem) TableName() string { 17 | return "tb_newbee_mall_order_item" 18 | } 19 | -------------------------------------------------------------------------------- /model/manage/manage_user.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "main.go/model/common" 5 | ) 6 | 7 | // MallUser 商城用户信息 8 | type MallUser struct { 9 | UserId int `json:"userId" form:"userId" gorm:"primarykey;AUTO_INCREMENT"` 10 | NickName string `json:"nickName" form:"nickName" gorm:"column:nick_name;comment:用户昵称;type:varchar(50);"` 11 | LoginName string `json:"loginName" form:"loginName" gorm:"column:login_name;comment:登陆名称(默认为手机号);type:varchar(11);"` 12 | PasswordMd5 string `json:"passwordMd5" form:"passwordMd5" gorm:"column:password_md5;comment:MD5加密后的密码;type:varchar(32);"` 13 | IntroduceSign string `json:"introduceSign" form:"introduceSign" gorm:"column:introduce_sign;comment:个性签名;type:varchar(100);"` 14 | IsDeleted int `json:"isDeleted" form:"isDeleted" gorm:"column:is_deleted;comment:注销标识字段(0-正常 1-已注销);type:tinyint"` 15 | LockedFlag int `json:"lockedFlag" form:"lockedFlag" gorm:"column:locked_flag;comment:锁定标识字段(0-未锁定 1-已锁定);type:tinyint"` 16 | CreateTime common.JSONTime `json:"createTime" form:"createTime" gorm:"column:create_time;comment:注册时间;type:datetime"` 17 | } 18 | 19 | // TableName MallUser 表名 20 | func (MallUser) TableName() string { 21 | return "tb_newbee_mall_user" 22 | } 23 | -------------------------------------------------------------------------------- /model/manage/request/manage_admin_user.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | type MallAdminLoginParam struct { 4 | UserName string `json:"userName"` 5 | PasswordMd5 string `json:"passwordMd5"` 6 | } 7 | type MallAdminParam struct { 8 | LoginUserName string `json:"loginUserName"` 9 | LoginPassword string `json:"loginPassword"` 10 | NickName string `json:"nickName"` 11 | } 12 | 13 | type MallUpdateNameParam struct { 14 | LoginUserName string `json:"loginUserName"` 15 | NickName string `json:"nickName"` 16 | } 17 | 18 | type MallUpdatePasswordParam struct { 19 | OriginalPassword string `json:"originalPassword"` 20 | NewPassword string `json:"newPassword"` 21 | } 22 | -------------------------------------------------------------------------------- /model/manage/request/manage_carousel.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "main.go/model/common/request" 5 | "main.go/model/manage" 6 | ) 7 | 8 | type MallCarouselSearch struct { 9 | manage.MallCarousel 10 | request.PageInfo 11 | } 12 | 13 | type MallCarouselAddParam struct { 14 | CarouselUrl string `json:"carouselUrl"` 15 | RedirectUrl string `json:"redirectUrl"` 16 | CarouselRank string `json:"carouselRank"` 17 | } 18 | 19 | type MallCarouselUpdateParam struct { 20 | CarouselId int `json:"carouselId"` 21 | CarouselUrl string `json:"carouselUrl"` 22 | RedirectUrl string `json:"redirectUrl"` 23 | CarouselRank string `json:"carouselRank" ` 24 | } 25 | -------------------------------------------------------------------------------- /model/manage/request/manage_goods_category.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "main.go/model/common" 5 | "main.go/model/common/request" 6 | ) 7 | 8 | type MallGoodsCategoryReq struct { 9 | CategoryId int `json:"categoryId"` 10 | CategoryLevel int `json:"categoryLevel" ` 11 | ParentId int `json:"parentId"` 12 | CategoryName string `json:"categoryName" ` 13 | CategoryRank string `json:"categoryRank" ` 14 | IsDeleted int `json:"isDeleted" ` 15 | CreateTime common.JSONTime `json:"createTime" ` // 创建时间 16 | UpdateTime common.JSONTime `json:"updateTime" ` // 更新时间 17 | } 18 | 19 | type SearchCategoryParams struct { 20 | CategoryLevel int `json:"categoryLevel" form:"categoryLevel"` 21 | ParentId int `json:"parentId" form:"parentId"` 22 | request.PageInfo 23 | } 24 | -------------------------------------------------------------------------------- /model/manage/request/manage_goods_info.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "main.go/model/common" 5 | "main.go/model/common/request" 6 | "main.go/model/manage" 7 | ) 8 | 9 | type MallGoodsInfoSearch struct { 10 | manage.MallGoodsInfo 11 | request.PageInfo 12 | } 13 | 14 | type GoodsInfoAddParam struct { 15 | GoodsName string `json:"goodsName"` 16 | GoodsIntro string `json:"goodsIntro"` 17 | GoodsCategoryId int `json:"goodsCategoryId"` 18 | GoodsCoverImg string `json:"goodsCoverImg"` 19 | GoodsCarousel string `json:"goodsCarousel"` 20 | GoodsDetailContent string `json:"goodsDetailContent"` 21 | OriginalPrice string `json:"originalPrice"` 22 | SellingPrice string `json:"sellingPrice"` 23 | StockNum string `json:"stockNum"` 24 | Tag string `json:"tag"` 25 | GoodsSellStatus string `json:"goodsSellStatus"` 26 | } 27 | 28 | // GoodsInfoUpdateParam 更新商品信息的入参 29 | type GoodsInfoUpdateParam struct { 30 | GoodsId string `json:"goodsId"` 31 | GoodsName string `json:"goodsName"` 32 | GoodsIntro string `json:"goodsIntro"` 33 | GoodsCategoryId int `json:"goodsCategoryId"` 34 | GoodsCoverImg string `json:"goodsCoverImg"` 35 | GoodsCarousel string `json:"goodsCarousel"` 36 | GoodsDetailContent string `json:"goodsDetailContent"` 37 | OriginalPrice string `json:"originalPrice"` 38 | SellingPrice int `json:"sellingPrice"` 39 | StockNum string `json:"stockNum"` 40 | Tag string `json:"tag"` 41 | GoodsSellStatus int `json:"goodsSellStatus"` 42 | UpdateUser int `json:"updateUser" form:"updateUser" gorm:"column:update_user;comment:修改者主键id;type:int"` 43 | UpdateTime common.JSONTime `json:"updateTime" form:"updateTime" gorm:"column:update_time;comment:商品修改时间;type:datetime"` 44 | } 45 | 46 | type StockNumDTO struct { 47 | GoodsId int `json:"goodsId"` 48 | GoodsCount int `json:"goodsCount"` 49 | } 50 | -------------------------------------------------------------------------------- /model/manage/request/manage_index_config.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "main.go/model/common/request" 5 | "main.go/model/manage" 6 | ) 7 | 8 | type MallIndexConfigSearch struct { 9 | manage.MallIndexConfig 10 | request.PageInfo 11 | } 12 | 13 | type MallIndexConfigAddParams struct { 14 | ConfigName string `json:"configName"` 15 | ConfigType int `json:"configType"` 16 | GoodsId string `json:"goodsId"` 17 | RedirectUrl string `json:"redirectUrl"` 18 | ConfigRank string `json:"configRank"` 19 | } 20 | 21 | type MallIndexConfigUpdateParams struct { 22 | ConfigId int `json:"configId"` 23 | ConfigName string `json:"configName"` 24 | RedirectUrl string `json:"redirectUrl"` 25 | ConfigType int `json:"configType"` 26 | GoodsId int `json:"goodsId"` 27 | ConfigRank string `json:"configRank"` 28 | } 29 | -------------------------------------------------------------------------------- /model/manage/request/manage_order.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "main.go/model/common/request" 5 | ) 6 | 7 | type MallOrderSearch struct { 8 | request.PageInfo 9 | } 10 | -------------------------------------------------------------------------------- /model/manage/request/manage_user.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "main.go/model/common/request" 5 | "main.go/model/manage" 6 | ) 7 | 8 | type MallUserSearch struct { 9 | manage.MallUser 10 | request.PageInfo 11 | } 12 | -------------------------------------------------------------------------------- /model/manage/response/manage_goods_category.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | import "main.go/model/manage" 4 | 5 | type GoodsCategoryResponse struct { 6 | GoodsCategory manage.MallGoodsCategory `json:"mallGoodsCategory"` 7 | } 8 | -------------------------------------------------------------------------------- /model/manage/response/manage_order.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | import "main.go/model/common" 4 | 5 | type NewBeeMallOrderDetailVO struct { 6 | OrderId int `json:"orderId"` 7 | OrderNo string `json:"orderNo"` 8 | TotalPrice int `json:"totalPrice"` 9 | PayType int `json:"payType"` 10 | PayTypeString string `json:"payTypeString"` 11 | OrderStatus int `json:"orderStatus"` 12 | OrderStatusString string `json:"orderStatusString"` 13 | CreateTime common.JSONTime `json:"createTime"` 14 | NewBeeMallOrderItemVOS []NewBeeMallOrderItemVO `json:"newBeeMallOrderItemVOS"` 15 | } 16 | 17 | type NewBeeMallOrderItemVO struct { 18 | GoodsId int `json:"goodsId"` 19 | GoodsName string `json:"goodsName"` 20 | GoodsCount int `json:"goodsCount"` 21 | GoodsCoverImg string `json:"goodsCoverImg"` 22 | SellingPrice int `json:"sellingPrice"` 23 | } 24 | -------------------------------------------------------------------------------- /router/enter.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "main.go/router/mall" 5 | "main.go/router/manage" 6 | ) 7 | 8 | type RouterGroup struct { 9 | Manage manage.ManageRouterGroup 10 | Mall mall.MallRouterGroup 11 | } 12 | 13 | var RouterGroupApp = new(RouterGroup) 14 | -------------------------------------------------------------------------------- /router/mall/enter.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | type MallRouterGroup struct { 4 | MallCarouselIndexRouter 5 | MallGoodsInfoIndexRouter 6 | MallUserRouter 7 | MallGoodsCategoryIndexRouter 8 | MallShopCartRouter 9 | MallOrderRouter 10 | } 11 | -------------------------------------------------------------------------------- /router/mall/mall_carousel.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | ) 7 | 8 | type MallCarouselIndexRouter struct { 9 | } 10 | 11 | func (m *MallCarouselIndexRouter) InitMallCarouselIndexRouter(Router *gin.RouterGroup) { 12 | mallCarouselRouter := Router.Group("v1") 13 | var mallCarouselApi = v1.ApiGroupApp.MallApiGroup.MallIndexApi 14 | { 15 | mallCarouselRouter.GET("index-infos", mallCarouselApi.MallIndexInfo) // 获取首页数据 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /router/mall/mall_goods_category.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | ) 7 | 8 | type MallGoodsCategoryIndexRouter struct { 9 | } 10 | 11 | func (m *MallGoodsInfoIndexRouter) InitMallGoodsCategoryIndexRouter(Router *gin.RouterGroup) { 12 | mallGoodsRouter := Router.Group("v1") 13 | var mallGoodsCategoryApi = v1.ApiGroupApp.MallApiGroup.MallGoodsCategoryApi 14 | { 15 | mallGoodsRouter.GET("categories", mallGoodsCategoryApi.GetGoodsCategory) // 获取分类数据 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /router/mall/mall_goods_info.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | ) 7 | 8 | type MallGoodsInfoIndexRouter struct { 9 | } 10 | 11 | func (m *MallGoodsInfoIndexRouter) InitMallGoodsInfoIndexRouter(Router *gin.RouterGroup) { 12 | mallGoodsRouter := Router.Group("v1") 13 | var mallGoodsInfoApi = v1.ApiGroupApp.MallApiGroup.MallGoodsInfoApi 14 | { 15 | mallGoodsRouter.GET("/search", mallGoodsInfoApi.GoodsSearch) // 商品搜索 16 | mallGoodsRouter.GET("/goods/detail/:id", mallGoodsInfoApi.GoodsDetail) //商品详情 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /router/mall/mall_order.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type MallOrderRouter struct { 10 | } 11 | 12 | func (m *MallOrderRouter) InitMallOrderRouter(Router *gin.RouterGroup) { 13 | mallOrderRouter := Router.Group("v1").Use(middleware.UserJWTAuth()) 14 | 15 | var mallOrderRouterApi = v1.ApiGroupApp.MallApiGroup.MallOrderApi 16 | { 17 | mallOrderRouter.GET("/paySuccess", mallOrderRouterApi.PaySuccess) //模拟支付成功回调的接口 18 | mallOrderRouter.PUT("/order/:orderNo/finish", mallOrderRouterApi.FinishOrder) //确认收货接口 19 | mallOrderRouter.PUT("/order/:orderNo/cancel", mallOrderRouterApi.CancelOrder) //取消订单接口 20 | mallOrderRouter.GET("/order/:orderNo", mallOrderRouterApi.OrderDetailPage) //订单详情接口 21 | mallOrderRouter.GET("/order", mallOrderRouterApi.OrderList) //订单列表接口 22 | mallOrderRouter.POST("/saveOrder", mallOrderRouterApi.SaveOrder) 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /router/mall/mall_shop_cart.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type MallShopCartRouter struct { 10 | } 11 | 12 | func (m *MallUserRouter) InitMallShopCartRouter(Router *gin.RouterGroup) { 13 | mallShopCartRouter := Router.Group("v1").Use(middleware.UserJWTAuth()) 14 | var mallShopCartApi = v1.ApiGroupApp.MallApiGroup.MallShopCartApi 15 | { 16 | mallShopCartRouter.GET("/shop-cart", mallShopCartApi.CartItemList) //购物车列表(网页移动端不分页) 17 | mallShopCartRouter.POST("/shop-cart", mallShopCartApi.SaveMallShoppingCartItem) //添加购物车 18 | mallShopCartRouter.PUT("/shop-cart", mallShopCartApi.UpdateMallShoppingCartItem) //修改购物车 19 | mallShopCartRouter.PUT("/shop-cart/:newBeeMallShoppingCartItemId", mallShopCartApi.DelMallShoppingCartItem) //删除购物车 20 | mallShopCartRouter.GET("/shop-cart/settle", mallShopCartApi.ToSettle) //根据购物项id数组查询购物项明细 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /router/mall/mall_user.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type MallUserRouter struct { 10 | } 11 | 12 | func (m *MallUserRouter) InitMallUserRouter(Router *gin.RouterGroup) { 13 | mallUserRouter := Router.Group("v1").Use(middleware.UserJWTAuth()) 14 | userRouter := Router.Group("v1") 15 | var mallUserApi = v1.ApiGroupApp.MallApiGroup.MallUserApi 16 | { 17 | mallUserRouter.PUT("/user/info", mallUserApi.UserInfoUpdate) //修改用户信息 18 | mallUserRouter.GET("/user/info", mallUserApi.GetUserInfo) //获取用户信息 19 | mallUserRouter.POST("/user/logout", mallUserApi.UserLogout) //登出 20 | } 21 | { 22 | userRouter.POST("/user/register", mallUserApi.UserRegister) //用户注册 23 | userRouter.POST("/user/login", mallUserApi.UserLogin) //登陆 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /router/mall/mall_user_address.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type MallUserAddressRouter struct { 10 | } 11 | 12 | func (m *MallUserRouter) InitMallUserAddressRouter(Router *gin.RouterGroup) { 13 | mallUserAddressRouter := Router.Group("v1").Use(middleware.UserJWTAuth()) 14 | var mallUserAddressApi = v1.ApiGroupApp.MallApiGroup.MallUserAddressApi 15 | { 16 | mallUserAddressRouter.GET("/address", mallUserAddressApi.AddressList) //用户地址 17 | mallUserAddressRouter.POST("/address", mallUserAddressApi.SaveUserAddress) //添加地址 18 | mallUserAddressRouter.PUT("/address", mallUserAddressApi.UpdateMallUserAddress) //修改用户地址 19 | mallUserAddressRouter.GET("/address/:addressId", mallUserAddressApi.GetMallUserAddress) //获取地址详情 20 | mallUserAddressRouter.GET("/address/default", mallUserAddressApi.GetMallUserDefaultAddress) //获取默认地址 21 | mallUserAddressRouter.DELETE("/address/:addressId", mallUserAddressApi.DeleteUserAddress) //删除地址 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /router/manage/enter.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | type ManageRouterGroup struct { 4 | ManageGoodsCategoryRouter 5 | ManageAdminUserRouter 6 | ManageGoodsInfoRouter 7 | ManageCarouselRouter 8 | ManageIndexConfigRouter 9 | ManageOrderRouter 10 | } 11 | -------------------------------------------------------------------------------- /router/manage/manage_admin_user.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type ManageAdminUserRouter struct { 10 | } 11 | 12 | func (r *ManageAdminUserRouter) InitManageAdminUserRouter(Router *gin.RouterGroup) { 13 | mallAdminUserRouter := Router.Group("v1").Use(middleware.AdminJWTAuth()) 14 | mallAdminUserWithoutRouter := Router.Group("v1") 15 | var mallAdminUserApi = v1.ApiGroupApp.ManageApiGroup.ManageAdminUserApi 16 | { 17 | mallAdminUserRouter.POST("createMallAdminUser", mallAdminUserApi.CreateAdminUser) // 新建MallAdminUser 18 | mallAdminUserRouter.PUT("adminUser/name", mallAdminUserApi.UpdateAdminUserName) // 更新MallAdminUser 19 | mallAdminUserRouter.PUT("adminUser/password", mallAdminUserApi.UpdateAdminUserPassword) 20 | mallAdminUserRouter.GET("users", mallAdminUserApi.UserList) 21 | mallAdminUserRouter.PUT("users/:lockStatus", mallAdminUserApi.LockUser) 22 | mallAdminUserRouter.GET("adminUser/profile", mallAdminUserApi.AdminUserProfile) // 根据ID获取 admin详情 23 | mallAdminUserRouter.DELETE("logout", mallAdminUserApi.AdminLogout) 24 | mallAdminUserRouter.POST("upload/file", mallAdminUserApi.UploadFile) //上传图片 25 | 26 | } 27 | { 28 | mallAdminUserWithoutRouter.POST("adminUser/login", mallAdminUserApi.AdminLogin) //管理员登陆 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /router/manage/manage_carousel.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type ManageCarouselRouter struct { 10 | } 11 | 12 | func (r *ManageCarouselRouter) InitManageCarouselRouter(Router *gin.RouterGroup) { 13 | mallCarouselRouter := Router.Group("v1").Use(middleware.AdminJWTAuth()) 14 | var mallCarouselApi = v1.ApiGroupApp.ManageApiGroup.ManageCarouselApi 15 | { 16 | mallCarouselRouter.POST("carousels", mallCarouselApi.CreateCarousel) // 新建MallCarousel 17 | mallCarouselRouter.DELETE("carousels", mallCarouselApi.DeleteCarousel) // 删除MallCarousel 18 | mallCarouselRouter.PUT("carousels", mallCarouselApi.UpdateCarousel) // 更新MallCarousel 19 | mallCarouselRouter.GET("carousels/:id", mallCarouselApi.FindCarousel) // 根据ID获取轮播图 20 | mallCarouselRouter.GET("carousels", mallCarouselApi.GetCarouselList) // 获取轮播图列表 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /router/manage/manage_goods_category.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type ManageGoodsCategoryRouter struct { 10 | } 11 | 12 | func (r *ManageGoodsCategoryRouter) InitManageGoodsCategoryRouter(Router *gin.RouterGroup) { 13 | goodsCategoryRouter := Router.Group("v1").Use(middleware.AdminJWTAuth()) 14 | 15 | var goodsCategoryApi = v1.ApiGroupApp.ManageApiGroup.ManageGoodsCategoryApi 16 | { 17 | goodsCategoryRouter.POST("categories", goodsCategoryApi.CreateCategory) 18 | goodsCategoryRouter.PUT("categories", goodsCategoryApi.UpdateCategory) 19 | goodsCategoryRouter.GET("categories", goodsCategoryApi.GetCategoryList) 20 | goodsCategoryRouter.GET("categories/:id", goodsCategoryApi.GetCategory) 21 | goodsCategoryRouter.DELETE("categories", goodsCategoryApi.DelCategory) 22 | goodsCategoryRouter.GET("categories4Select", goodsCategoryApi.ListForSelect) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /router/manage/manage_goods_info.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | ) 7 | 8 | type ManageGoodsInfoRouter struct { 9 | } 10 | 11 | func (m *ManageGoodsInfoRouter) InitManageGoodsInfoRouter(Router *gin.RouterGroup) { 12 | mallGoodsInfoRouter := Router.Group("v1") 13 | var mallGoodsInfoApi = v1.ApiGroupApp.ManageApiGroup.ManageGoodsInfoApi 14 | { 15 | mallGoodsInfoRouter.POST("goods", mallGoodsInfoApi.CreateGoodsInfo) // 新建MallGoodsInfo 16 | mallGoodsInfoRouter.DELETE("deleteMallGoodsInfo", mallGoodsInfoApi.DeleteGoodsInfo) // 删除MallGoodsInfo 17 | mallGoodsInfoRouter.PUT("goods/status/:status", mallGoodsInfoApi.ChangeGoodsInfoByIds) // 上下架 18 | mallGoodsInfoRouter.PUT("goods", mallGoodsInfoApi.UpdateGoodsInfo) // 更新MallGoodsInfo 19 | mallGoodsInfoRouter.GET("goods/:id", mallGoodsInfoApi.FindGoodsInfo) // 根据ID获取MallGoodsInfo 20 | mallGoodsInfoRouter.GET("goods/list", mallGoodsInfoApi.GetGoodsInfoList) // 获取MallGoodsInfo列表 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /router/manage/manage_index_config.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | ) 7 | 8 | type ManageIndexConfigRouter struct { 9 | } 10 | 11 | func (r *ManageIndexConfigRouter) InitManageIndexConfigRouter(Router *gin.RouterGroup) { 12 | mallIndexConfigRouter := Router.Group("v1") 13 | var mallIndexConfigApi = v1.ApiGroupApp.ManageApiGroup.ManageIndexConfigApi 14 | { 15 | mallIndexConfigRouter.POST("indexConfigs", mallIndexConfigApi.CreateIndexConfig) // 新建MallIndexConfig 16 | mallIndexConfigRouter.POST("indexConfigs/delete", mallIndexConfigApi.DeleteIndexConfig) // 删除MallIndexConfig 17 | mallIndexConfigRouter.PUT("indexConfigs", mallIndexConfigApi.UpdateIndexConfig) // 更新MallIndexConfig 18 | mallIndexConfigRouter.GET("indexConfigs/:id", mallIndexConfigApi.FindIndexConfig) // 根据ID获取MallIndexConfig 19 | mallIndexConfigRouter.GET("indexConfigs", mallIndexConfigApi.GetIndexConfigList) // 获取MallIndexConfig列表 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /router/manage/manage_order.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | v1 "main.go/api/v1" 6 | "main.go/middleware" 7 | ) 8 | 9 | type ManageOrderRouter struct { 10 | } 11 | 12 | func (r *ManageOrderRouter) InitManageOrderRouter(Router *gin.RouterGroup) { 13 | mallOrderRouter := Router.Group("v1").Use(middleware.AdminJWTAuth()) 14 | var mallOrderApi = v1.ApiGroupApp.ManageApiGroup.ManageOrderApi 15 | { 16 | mallOrderRouter.PUT("orders/checkDone", mallOrderApi.CheckDoneOrder) // 发货 17 | mallOrderRouter.PUT("orders/checkOut", mallOrderApi.CheckOutOrder) // 出库 18 | mallOrderRouter.PUT("orders/close", mallOrderApi.CloseOrder) // 出库 19 | mallOrderRouter.GET("orders/:orderId", mallOrderApi.FindMallOrder) // 根据ID获取MallOrder 20 | mallOrderRouter.GET("orders", mallOrderApi.GetMallOrderList) // 获取MallOrder列表 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /service/enter.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "main.go/service/example" 5 | "main.go/service/mall" 6 | "main.go/service/manage" 7 | ) 8 | 9 | type ServiceGroup struct { 10 | ExampleServiceGroup example.ServiceGroup 11 | ManageServiceGroup manage.ManageServiceGroup 12 | MallServiceGroup mall.MallServiceGroup 13 | } 14 | 15 | var ServiceGroupApp = new(ServiceGroup) 16 | -------------------------------------------------------------------------------- /service/example/enter.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | type ServiceGroup struct { 4 | FileUploadAndDownloadService 5 | } 6 | -------------------------------------------------------------------------------- /service/example/exa_breakpoint_continue.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import ( 4 | "errors" 5 | "gorm.io/gorm" 6 | "main.go/global" 7 | "main.go/model/example" 8 | ) 9 | 10 | type FileUploadAndDownloadService struct { 11 | } 12 | 13 | //@author: [piexlmax](https://github.com/piexlmax) 14 | //@function: FindOrCreateFile 15 | //@description: 上传文件时检测当前文件属性,如果没有文件则创建,有则返回文件的当前切片 16 | //@param: fileMd5 string, fileName string, chunkTotal int 17 | //@return: err error, file model.ExaFile 18 | 19 | func (e *FileUploadAndDownloadService) FindOrCreateFile(fileMd5 string, fileName string, chunkTotal int) (err error, file example.ExaFile) { 20 | var cfile example.ExaFile 21 | cfile.FileMd5 = fileMd5 22 | cfile.FileName = fileName 23 | cfile.ChunkTotal = chunkTotal 24 | 25 | if errors.Is(global.GVA_DB.Where("file_md5 = ? AND is_finish = ?", fileMd5, true).First(&file).Error, gorm.ErrRecordNotFound) { 26 | err = global.GVA_DB.Where("file_md5 = ? AND file_name = ?", fileMd5, fileName).Preload("ExaFileChunk").FirstOrCreate(&file, cfile).Error 27 | return err, file 28 | } 29 | cfile.IsFinish = true 30 | cfile.FilePath = file.FilePath 31 | err = global.GVA_DB.Create(&cfile).Error 32 | return err, cfile 33 | } 34 | 35 | //@author: [piexlmax](https://github.com/piexlmax) 36 | //@function: CreateFileChunk 37 | //@description: 创建文件切片记录 38 | //@param: id uint, fileChunkPath string, fileChunkNumber int 39 | //@return: error 40 | 41 | func (e *FileUploadAndDownloadService) CreateFileChunk(id uint, fileChunkPath string, fileChunkNumber int) error { 42 | var chunk example.ExaFileChunk 43 | chunk.FileChunkPath = fileChunkPath 44 | chunk.ExaFileID = id 45 | chunk.FileChunkNumber = fileChunkNumber 46 | err := global.GVA_DB.Create(&chunk).Error 47 | return err 48 | } 49 | 50 | //@author: [piexlmax](https://github.com/piexlmax) 51 | //@function: DeleteFileChunk 52 | //@description: 删除文件切片记录 53 | //@param: fileMd5 string, fileName string, filePath string 54 | //@return: error 55 | 56 | func (e *FileUploadAndDownloadService) DeleteFileChunk(fileMd5 string, fileName string, filePath string) error { 57 | var chunks []example.ExaFileChunk 58 | var file example.ExaFile 59 | err := global.GVA_DB.Where("file_md5 = ? AND file_name = ?", fileMd5, fileName).First(&file).Update("IsFinish", true).Update("file_path", filePath).Error 60 | if err != nil { 61 | return err 62 | } 63 | err = global.GVA_DB.Where("exa_file_id = ?", file.ID).Delete(&chunks).Unscoped().Error 64 | return err 65 | } 66 | -------------------------------------------------------------------------------- /service/example/exa_file_upload_download.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import ( 4 | "errors" 5 | "main.go/global" 6 | "main.go/model/common/request" 7 | "main.go/model/example" 8 | "main.go/utils/upload" 9 | "mime/multipart" 10 | "strings" 11 | ) 12 | 13 | //@author: [piexlmax](https://github.com/piexlmax) 14 | //@function: Upload 15 | //@description: 创建文件上传记录 16 | //@param: file model.ExaFileUploadAndDownload 17 | //@return: error 18 | 19 | func (e *FileUploadAndDownloadService) Upload(file example.ExaFileUploadAndDownload) error { 20 | return global.GVA_DB.Create(&file).Error 21 | } 22 | 23 | //@author: [piexlmax](https://github.com/piexlmax) 24 | //@function: FindFile 25 | //@description: 删除文件切片记录 26 | //@param: id uint 27 | //@return: error, model.ExaFileUploadAndDownload 28 | 29 | func (e *FileUploadAndDownloadService) FindFile(id int) (error, example.ExaFileUploadAndDownload) { 30 | var file example.ExaFileUploadAndDownload 31 | err := global.GVA_DB.Where("id = ?", id).First(&file).Error 32 | return err, file 33 | } 34 | 35 | //@author: [piexlmax](https://github.com/piexlmax) 36 | //@function: DeleteFile 37 | //@description: 删除文件记录 38 | //@param: file model.ExaFileUploadAndDownload 39 | //@return: err error 40 | 41 | func (e *FileUploadAndDownloadService) DeleteFile(file example.ExaFileUploadAndDownload) (err error) { 42 | var fileFromDb example.ExaFileUploadAndDownload 43 | err, fileFromDb = e.FindFile(file.ID) 44 | if err != nil { 45 | return 46 | } 47 | oss := upload.NewOss() 48 | if err = oss.DeleteFile(fileFromDb.Key); err != nil { 49 | return errors.New("文件删除失败") 50 | } 51 | err = global.GVA_DB.Where("id = ?", file.ID).Unscoped().Delete(&file).Error 52 | return err 53 | } 54 | 55 | //@author: [piexlmax](https://github.com/piexlmax) 56 | //@function: GetFileRecordInfoList 57 | //@description: 分页获取数据 58 | //@param: info request.PageInfo 59 | //@return: err error, list interface{}, total int64 60 | 61 | func (e *FileUploadAndDownloadService) GetFileRecordInfoList(info request.PageInfo) (err error, list interface{}, total int64) { 62 | limit := info.PageSize 63 | offset := info.PageSize * (info.PageNumber - 1) 64 | db := global.GVA_DB.Model(&example.ExaFileUploadAndDownload{}) 65 | var fileLists []example.ExaFileUploadAndDownload 66 | err = db.Count(&total).Error 67 | if err != nil { 68 | return 69 | } 70 | err = db.Limit(limit).Offset(offset).Order("updated_at desc").Find(&fileLists).Error 71 | return err, fileLists, total 72 | } 73 | 74 | //@author: [piexlmax](https://github.com/piexlmax) 75 | //@function: UploadFile 76 | //@description: 根据配置文件判断是文件上传到本地或者七牛云 77 | //@param: header *multipart.FileHeader, noSave string 78 | //@return: err error, file model.ExaFileUploadAndDownload 79 | 80 | func (e *FileUploadAndDownloadService) UploadFile(header *multipart.FileHeader, noSave string) (err error, file example.ExaFileUploadAndDownload) { 81 | oss := upload.NewOss() 82 | filePath, key, uploadErr := oss.UploadFile(header) 83 | if uploadErr != nil { 84 | panic(err) 85 | } 86 | if noSave == "0" { 87 | s := strings.Split(header.Filename, ".") 88 | f := example.ExaFileUploadAndDownload{ 89 | Url: filePath, 90 | Name: header.Filename, 91 | Tag: s[len(s)-1], 92 | Key: key, 93 | } 94 | return err, f 95 | } 96 | return 97 | } 98 | -------------------------------------------------------------------------------- /service/mall/enter.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | type MallServiceGroup struct { 4 | MallIndexInfoService 5 | MallCarouselService 6 | MallGoodsInfoService 7 | MallGoodsCategoryService 8 | MallUserService 9 | MallUserTokenService 10 | MallUserAddressService 11 | MallShopCartService 12 | MallOrderService 13 | } 14 | -------------------------------------------------------------------------------- /service/mall/mall_carousel.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "main.go/global" 5 | "main.go/model/mall/response" 6 | "main.go/model/manage" 7 | ) 8 | 9 | type MallCarouselService struct { 10 | } 11 | 12 | // GetCarouselsForIndex 返回固定数量的轮播图对象(首页调用) 13 | func (m *MallCarouselService) GetCarouselsForIndex(num int) (err error, mallCarousels []manage.MallCarousel, list interface{}) { 14 | var carouselIndexs []response.MallCarouselIndexResponse 15 | err = global.GVA_DB.Where("is_deleted = 0").Order("carousel_rank desc").Limit(num).Find(&mallCarousels).Error 16 | for _, carousel := range mallCarousels { 17 | carouselIndex := response.MallCarouselIndexResponse{ 18 | CarouselUrl: carousel.CarouselUrl, 19 | RedirectUrl: carousel.RedirectUrl, 20 | } 21 | carouselIndexs = append(carouselIndexs, carouselIndex) 22 | } 23 | return err, mallCarousels, carouselIndexs 24 | } 25 | -------------------------------------------------------------------------------- /service/mall/mall_goods_category.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "github.com/jinzhu/copier" 5 | "main.go/global" 6 | "main.go/model/common/enum" 7 | mallRes "main.go/model/mall/response" 8 | "main.go/model/manage" 9 | ) 10 | 11 | type MallGoodsCategoryService struct { 12 | } 13 | 14 | func (m *MallGoodsCategoryService) GetCategoriesForIndex() (err error, newBeeMallIndexCategoryVOS []mallRes.NewBeeMallIndexCategoryVO) { 15 | 16 | //获取一级分类的固定数量的数据 17 | _, firstLevelCategories := selectByLevelAndParentIdsAndNumber([]int{0}, enum.LevelOne.Code(), 10) 18 | if firstLevelCategories != nil { 19 | var firstLevelCategoryIds []int 20 | for _, firstLevelCategory := range firstLevelCategories { 21 | firstLevelCategoryIds = append(firstLevelCategoryIds, firstLevelCategory.CategoryId) 22 | } 23 | //获取二级分类的数据 24 | _, secondLevelCategories := selectByLevelAndParentIdsAndNumber(firstLevelCategoryIds, enum.LevelTwo.Code(), 0) 25 | if secondLevelCategories != nil { 26 | var secondLevelCategoryIds []int 27 | for _, secondLevelCategory := range secondLevelCategories { 28 | secondLevelCategoryIds = append(secondLevelCategoryIds, secondLevelCategory.CategoryId) 29 | } 30 | //获取三级分类的数据 31 | _, thirdLevelCategories := selectByLevelAndParentIdsAndNumber(secondLevelCategoryIds, enum.LevelThree.Code(), 0) 32 | if thirdLevelCategories != nil { 33 | //根据 parentId 将 thirdLevelCategories 分组 34 | thirdLevelCategoryMap := make(map[int][]manage.MallGoodsCategory) 35 | for _, thirdLevelCategory := range thirdLevelCategories { 36 | thirdLevelCategoryMap[thirdLevelCategory.ParentId] = []manage.MallGoodsCategory{} 37 | } 38 | for k, v := range thirdLevelCategoryMap { 39 | for _, third := range thirdLevelCategories { 40 | if k == third.ParentId { 41 | v = append(v, third) 42 | } 43 | thirdLevelCategoryMap[k] = v 44 | } 45 | } 46 | var secondLevelCategoryVOS []mallRes.SecondLevelCategoryVO 47 | //处理二级分类 48 | for _, secondLevelCategory := range secondLevelCategories { 49 | var secondLevelCategoryVO mallRes.SecondLevelCategoryVO 50 | err = copier.Copy(&secondLevelCategoryVO, &secondLevelCategory) 51 | //如果该二级分类下有数据则放入 secondLevelCategoryVOS 对象中 52 | if _, ok := thirdLevelCategoryMap[secondLevelCategory.CategoryId]; ok { 53 | //根据二级分类的id取出thirdLevelCategoryMap分组中的三级分类list 54 | tempGoodsCategories := thirdLevelCategoryMap[secondLevelCategory.CategoryId] 55 | var thirdLevelCategoryRes []mallRes.ThirdLevelCategoryVO 56 | err = copier.Copy(&thirdLevelCategoryRes, &tempGoodsCategories) 57 | secondLevelCategoryVO.ThirdLevelCategoryVOS = thirdLevelCategoryRes 58 | secondLevelCategoryVOS = append(secondLevelCategoryVOS, secondLevelCategoryVO) 59 | } 60 | 61 | } 62 | //处理一级分类 63 | if secondLevelCategoryVOS != nil { 64 | //根据 parentId 将 thirdLevelCategories 分组 65 | secondLevelCategoryVOMap := make(map[int][]mallRes.SecondLevelCategoryVO) 66 | for _, secondLevelCategory := range secondLevelCategoryVOS { 67 | secondLevelCategoryVOMap[secondLevelCategory.ParentId] = []mallRes.SecondLevelCategoryVO{} 68 | } 69 | for k, v := range secondLevelCategoryVOMap { 70 | for _, second := range secondLevelCategoryVOS { 71 | if k == second.ParentId { 72 | var secondLevelCategory mallRes.SecondLevelCategoryVO 73 | copier.Copy(&secondLevelCategory, &second) 74 | v = append(v, secondLevelCategory) 75 | } 76 | secondLevelCategoryVOMap[k] = v 77 | } 78 | } 79 | for _, firstCategory := range firstLevelCategories { 80 | var newBeeMallIndexCategoryVO mallRes.NewBeeMallIndexCategoryVO 81 | err = copier.Copy(&newBeeMallIndexCategoryVO, &firstCategory) 82 | //如果该一级分类下有数据则放入 newBeeMallIndexCategoryVOS 对象中 83 | if _, ok := secondLevelCategoryVOMap[firstCategory.CategoryId]; ok { 84 | //根据一级分类的id取出secondLevelCategoryVOMap分组中的二级级分类list 85 | tempGoodsCategories := secondLevelCategoryVOMap[firstCategory.CategoryId] 86 | newBeeMallIndexCategoryVO.SecondLevelCategoryVOS = tempGoodsCategories 87 | newBeeMallIndexCategoryVOS = append(newBeeMallIndexCategoryVOS, newBeeMallIndexCategoryVO) 88 | } 89 | } 90 | } 91 | } 92 | } 93 | } 94 | return 95 | } 96 | 97 | // 获取分类数据 98 | func selectByLevelAndParentIdsAndNumber(ids []int, level int, limit int) (err error, categories []manage.MallGoodsCategory) { 99 | 100 | global.GVA_DB.Where("parent_id in ? and category_level =? and is_deleted = 0", ids, level). 101 | Order("category_rank desc").Limit(limit).Find(&categories) 102 | return 103 | } 104 | -------------------------------------------------------------------------------- /service/mall/mall_goods_info.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "errors" 5 | "github.com/jinzhu/copier" 6 | "main.go/global" 7 | mallRes "main.go/model/mall/response" 8 | "main.go/model/manage" 9 | "main.go/utils" 10 | ) 11 | 12 | type MallGoodsInfoService struct { 13 | } 14 | 15 | func (m *MallGoodsInfoService) MallGoodsListBySearch(pageNumber int, goodsCategoryId int, keyword string, orderBy string) (err error, searchGoodsList []mallRes.GoodsSearchResponse, total int64) { 16 | // 根据搜索条件查询 17 | var goodsList []manage.MallGoodsInfo 18 | db := global.GVA_DB.Model(&manage.MallGoodsInfo{}) 19 | if keyword != "" { 20 | db.Where("goods_name like ? or goods_intro like ?", "%"+keyword+"%", "%"+keyword+"%") 21 | } 22 | if goodsCategoryId >= 0 { 23 | db.Where("goods_category_id= ?", goodsCategoryId) 24 | } 25 | err = db.Count(&total).Error 26 | switch orderBy { 27 | case "new": 28 | db.Order("goods_id desc") 29 | case "price": 30 | db.Order("selling_price asc") 31 | default: 32 | db.Order("stock_num desc") 33 | } 34 | limit := 10 35 | offset := 10 * (pageNumber - 1) 36 | err = db.Limit(limit).Offset(offset).Find(&goodsList).Error 37 | // 返回查询结果 38 | for _, goods := range goodsList { 39 | searchGoods := mallRes.GoodsSearchResponse{ 40 | GoodsId: goods.GoodsId, 41 | GoodsName: utils.SubStrLen(goods.GoodsName, 28), 42 | GoodsIntro: utils.SubStrLen(goods.GoodsIntro, 28), 43 | GoodsCoverImg: goods.GoodsCoverImg, 44 | SellingPrice: goods.SellingPrice, 45 | } 46 | searchGoodsList = append(searchGoodsList, searchGoods) 47 | } 48 | 49 | return 50 | } 51 | 52 | func (m *MallGoodsInfoService) GetMallGoodsInfo(id int) (err error, res mallRes.GoodsInfoDetailResponse) { 53 | var mallGoodsInfo manage.MallGoodsInfo 54 | err = global.GVA_DB.Where("goods_id = ?", id).First(&mallGoodsInfo).Error 55 | if mallGoodsInfo.GoodsSellStatus != 0 { 56 | return errors.New("商品已下架"), mallRes.GoodsInfoDetailResponse{} 57 | } 58 | err = copier.Copy(&res, &mallGoodsInfo) 59 | if err != nil { 60 | return err, mallRes.GoodsInfoDetailResponse{} 61 | } 62 | var list []string 63 | list = append(list, mallGoodsInfo.GoodsCarousel) 64 | res.GoodsCarouselList = list 65 | 66 | return 67 | } 68 | -------------------------------------------------------------------------------- /service/mall/mall_index_info.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "main.go/global" 5 | "main.go/model/mall/response" 6 | "main.go/model/manage" 7 | "main.go/utils" 8 | ) 9 | 10 | type MallIndexInfoService struct { 11 | } 12 | 13 | // 首页返回相关IndexConfig 14 | func (m *MallIndexInfoService) GetConfigGoodsForIndex(configType int, num int) (err error, list interface{}) { 15 | var indexConfigs []manage.MallIndexConfig 16 | err = global.GVA_DB.Where("config_type = ?", configType).Where("is_deleted = 0").Order("config_rank desc").Limit(num).Find(&indexConfigs).Error 17 | if err != nil { 18 | return 19 | } 20 | // 获取商品id 21 | var ids []int 22 | for _, indexConfig := range indexConfigs { 23 | ids = append(ids, indexConfig.GoodsId) 24 | } 25 | // 获取商品信息 26 | var goodsList []manage.MallGoodsInfo 27 | err = global.GVA_DB.Where("goods_id in ?", ids).Find(&goodsList).Error 28 | 29 | var indexGoodsList []response.MallIndexConfigGoodsResponse 30 | // 超出30个字符显示.... 31 | for _, indexGoods := range goodsList { 32 | res := response.MallIndexConfigGoodsResponse{ 33 | GoodsId: indexGoods.GoodsId, 34 | GoodsName: utils.SubStrLen(indexGoods.GoodsName, 30), 35 | GoodsIntro: utils.SubStrLen(indexGoods.GoodsIntro, 30), 36 | GoodsCoverImg: indexGoods.GoodsCoverImg, 37 | SellingPrice: indexGoods.SellingPrice, 38 | Tag: indexGoods.Tag, 39 | } 40 | indexGoodsList = append(indexGoodsList, res) 41 | } 42 | return err, indexGoodsList 43 | } 44 | -------------------------------------------------------------------------------- /service/mall/mall_order.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "errors" 5 | "github.com/jinzhu/copier" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/common/enum" 9 | "main.go/model/mall" 10 | mallRes "main.go/model/mall/response" 11 | "main.go/model/manage" 12 | manageReq "main.go/model/manage/request" 13 | "main.go/utils" 14 | "time" 15 | ) 16 | 17 | type MallOrderService struct { 18 | } 19 | 20 | func (m *MallOrderService) SaveOrder(token string, userAddress mall.MallUserAddress, myShoppingCartItems []mallRes.CartItemResponse) (err error, orderNo string) { 21 | var userToken mall.MallUserToken 22 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 23 | if err != nil { 24 | return errors.New("不存在的用户"), orderNo 25 | } 26 | 27 | var itemIdList []int 28 | var goodsIds []int 29 | for _, cartItem := range myShoppingCartItems { 30 | itemIdList = append(itemIdList, cartItem.CartItemId) 31 | goodsIds = append(goodsIds, cartItem.GoodsId) 32 | } 33 | 34 | var newBeeMallGoods []manage.MallGoodsInfo 35 | global.GVA_DB.Where("goods_id in ? ", goodsIds).Find(&newBeeMallGoods) 36 | //检查是否包含已下架商品 37 | for _, mallGoods := range newBeeMallGoods { 38 | if mallGoods.GoodsSellStatus != 0 { 39 | return errors.New("已下架,无法生成订单"), orderNo 40 | } 41 | } 42 | newBeeMallGoodsMap := make(map[int]manage.MallGoodsInfo) 43 | for _, mallGoods := range newBeeMallGoods { 44 | newBeeMallGoodsMap[mallGoods.GoodsId] = mallGoods 45 | } 46 | //判断商品库存 47 | for _, shoppingCartItemVO := range myShoppingCartItems { 48 | //查出的商品中不存在购物车中的这条关联商品数据,直接返回错误提醒 49 | if _, ok := newBeeMallGoodsMap[shoppingCartItemVO.GoodsId]; !ok { 50 | return errors.New("购物车数据异常!"), orderNo 51 | } 52 | if shoppingCartItemVO.GoodsCount > newBeeMallGoodsMap[shoppingCartItemVO.GoodsId].StockNum { 53 | return errors.New("库存不足!"), orderNo 54 | } 55 | } 56 | 57 | //删除购物项 58 | if len(itemIdList) > 0 && len(goodsIds) > 0 { 59 | if err = global.GVA_DB.Where("cart_item_id in ?", itemIdList).Updates(mall.MallShoppingCartItem{IsDeleted: 1}).Error; err == nil { 60 | var stockNumDTOS []manageReq.StockNumDTO 61 | copier.Copy(&stockNumDTOS, &myShoppingCartItems) 62 | for _, stockNumDTO := range stockNumDTOS { 63 | var goodsInfo manage.MallGoodsInfo 64 | global.GVA_DB.Where("goods_id =?", stockNumDTO.GoodsId).First(&goodsInfo) 65 | if err = global.GVA_DB.Where("goods_id =? and stock_num>= ? and goods_sell_status = 0", stockNumDTO.GoodsId, stockNumDTO.GoodsCount).Updates(manage.MallGoodsInfo{StockNum: goodsInfo.StockNum - stockNumDTO.GoodsCount}).Error; err != nil { 66 | return errors.New("库存不足!"), orderNo 67 | } 68 | } 69 | //生成订单号 70 | orderNo = utils.GenOrderNo() 71 | priceTotal := 0 72 | //保存订单 73 | var newBeeMallOrder manage.MallOrder 74 | newBeeMallOrder.OrderNo = orderNo 75 | newBeeMallOrder.UserId = userToken.UserId 76 | //总价 77 | for _, newBeeMallShoppingCartItemVO := range myShoppingCartItems { 78 | priceTotal = priceTotal + newBeeMallShoppingCartItemVO.GoodsCount*newBeeMallShoppingCartItemVO.SellingPrice 79 | } 80 | if priceTotal < 1 { 81 | return errors.New("订单价格异常!"), orderNo 82 | } 83 | newBeeMallOrder.CreateTime = common.JSONTime{Time: time.Now()} 84 | newBeeMallOrder.UpdateTime = common.JSONTime{Time: time.Now()} 85 | newBeeMallOrder.TotalPrice = priceTotal 86 | newBeeMallOrder.ExtraInfo = "" 87 | //生成订单项并保存订单项纪录 88 | if err = global.GVA_DB.Save(&newBeeMallOrder).Error; err != nil { 89 | return errors.New("订单入库失败!"), orderNo 90 | } 91 | //生成订单收货地址快照,并保存至数据库 92 | var newBeeMallOrderAddress mall.MallOrderAddress 93 | copier.Copy(&newBeeMallOrderAddress, &userAddress) 94 | newBeeMallOrderAddress.OrderId = newBeeMallOrder.OrderId 95 | //生成所有的订单项快照,并保存至数据库 96 | var newBeeMallOrderItems []manage.MallOrderItem 97 | for _, newBeeMallShoppingCartItemVO := range myShoppingCartItems { 98 | var newBeeMallOrderItem manage.MallOrderItem 99 | copier.Copy(&newBeeMallOrderItem, &newBeeMallShoppingCartItemVO) 100 | newBeeMallOrderItem.OrderId = newBeeMallOrder.OrderId 101 | newBeeMallOrderItem.CreateTime = common.JSONTime{Time: time.Now()} 102 | newBeeMallOrderItems = append(newBeeMallOrderItems, newBeeMallOrderItem) 103 | } 104 | if err = global.GVA_DB.Save(&newBeeMallOrderItems).Error; err != nil { 105 | return err, orderNo 106 | } 107 | } 108 | } 109 | return 110 | } 111 | 112 | func (m *MallOrderService) PaySuccess(orderNo string, payType int) (err error) { 113 | var mallOrder manage.MallOrder 114 | err = global.GVA_DB.Where("order_no = ? and is_deleted=0 ", orderNo).First(&mallOrder).Error 115 | if mallOrder != (manage.MallOrder{}) { 116 | if mallOrder.OrderStatus != 0 { 117 | return errors.New("订单状态异常!") 118 | } 119 | mallOrder.OrderStatus = 1 120 | mallOrder.PayType = payType 121 | mallOrder.PayStatus = 1 122 | mallOrder.PayTime = common.JSONTime{time.Now()} 123 | mallOrder.UpdateTime = common.JSONTime{time.Now()} 124 | err = global.GVA_DB.Save(&mallOrder).Error 125 | } 126 | return 127 | } 128 | 129 | func (m *MallOrderService) FinishOrder(token string, orderNo string) (err error) { 130 | var userToken mall.MallUserToken 131 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 132 | if err != nil { 133 | return errors.New("不存在的用户") 134 | } 135 | var mallOrder manage.MallOrder 136 | if err = global.GVA_DB.Where("order_no=? and is_deleted = 0", orderNo).First(&mallOrder).Error; err != nil { 137 | return errors.New("未查询到记录!") 138 | } 139 | if mallOrder.UserId != userToken.UserId { 140 | return errors.New("禁止该操作!") 141 | } 142 | mallOrder.OrderStatus = enum.ORDER_SUCCESS.Code() 143 | mallOrder.UpdateTime = common.JSONTime{time.Now()} 144 | err = global.GVA_DB.Save(&mallOrder).Error 145 | return 146 | } 147 | 148 | func (m *MallOrderService) CancelOrder(token string, orderNo string) (err error) { 149 | var userToken mall.MallUserToken 150 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 151 | if err != nil { 152 | return errors.New("不存在的用户") 153 | } 154 | var mallOrder manage.MallOrder 155 | if err = global.GVA_DB.Where("order_no=? and is_deleted = 0", orderNo).First(&mallOrder).Error; err != nil { 156 | return errors.New("未查询到记录!") 157 | } 158 | if mallOrder.UserId != userToken.UserId { 159 | return errors.New("禁止该操作!") 160 | } 161 | if utils.NumsInList(mallOrder.OrderStatus, []int{enum.ORDER_SUCCESS.Code(), 162 | enum.ORDER_CLOSED_BY_MALLUSER.Code(), enum.ORDER_CLOSED_BY_EXPIRED.Code(), enum.ORDER_CLOSED_BY_JUDGE.Code()}) { 163 | return errors.New("订单状态异常!") 164 | } 165 | mallOrder.OrderStatus = enum.ORDER_CLOSED_BY_MALLUSER.Code() 166 | mallOrder.UpdateTime = common.JSONTime{time.Now()} 167 | err = global.GVA_DB.Save(&mallOrder).Error 168 | return 169 | } 170 | 171 | func (m *MallOrderService) GetOrderDetailByOrderNo(token string, orderNo string) (err error, orderDetail mallRes.MallOrderDetailVO) { 172 | var userToken mall.MallUserToken 173 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 174 | if err != nil { 175 | return errors.New("不存在的用户"), orderDetail 176 | } 177 | var mallOrder manage.MallOrder 178 | if err = global.GVA_DB.Where("order_no=? and is_deleted = 0", orderNo).First(&mallOrder).Error; err != nil { 179 | return errors.New("未查询到记录!"), orderDetail 180 | } 181 | if mallOrder.UserId != userToken.UserId { 182 | return errors.New("禁止该操作!"), orderDetail 183 | } 184 | var orderItems []manage.MallOrderItem 185 | err = global.GVA_DB.Where("order_id = ?", mallOrder.OrderId).Find(&orderItems).Error 186 | if len(orderItems) <= 0 { 187 | return errors.New("订单项不存在!"), orderDetail 188 | } 189 | 190 | var newBeeMallOrderItemVOS []mallRes.NewBeeMallOrderItemVO 191 | copier.Copy(&newBeeMallOrderItemVOS, &orderItems) 192 | copier.Copy(&orderDetail, &mallOrder) 193 | // 订单状态前端显示为中文 194 | _, OrderStatusStr := enum.GetNewBeeMallOrderStatusEnumByStatus(orderDetail.OrderStatus) 195 | _, payTapStr := enum.GetNewBeeMallOrderStatusEnumByStatus(orderDetail.PayType) 196 | orderDetail.OrderStatusString = OrderStatusStr 197 | orderDetail.PayTypeString = payTapStr 198 | orderDetail.NewBeeMallOrderItemVOS = newBeeMallOrderItemVOS 199 | 200 | return 201 | } 202 | 203 | func (m *MallOrderService) MallOrderListBySearch(token string, pageNumber int, status string) (err error, list []mallRes.MallOrderResponse, total int64) { 204 | var userToken mall.MallUserToken 205 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 206 | if err != nil { 207 | return errors.New("不存在的用户"), list, total 208 | } 209 | // 根据搜索条件查询 210 | var newBeeMallOrders []manage.MallOrder 211 | db := global.GVA_DB.Model(&newBeeMallOrders) 212 | 213 | if status != "" { 214 | db.Where("order_status = ?", status) 215 | } 216 | err = db.Where("user_id =? and is_deleted=0 ", userToken.UserId).Count(&total).Error 217 | limit := 5 218 | offset := 5 * (pageNumber - 1) 219 | err = db.Limit(limit).Offset(offset).Find(&newBeeMallOrders).Error 220 | 221 | var orderListVOS []mallRes.MallOrderResponse 222 | if total > 0 { 223 | //数据转换 将实体类转成vo 224 | copier.Copy(&orderListVOS, &newBeeMallOrders) 225 | //设置订单状态中文显示值 226 | for _, newBeeMallOrderListVO := range orderListVOS { 227 | _, statusStr := enum.GetNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderListVO.OrderStatus) 228 | newBeeMallOrderListVO.OrderStatusString = statusStr 229 | } 230 | // 返回订单id 231 | var orderIds []int 232 | for _, order := range newBeeMallOrders { 233 | orderIds = append(orderIds, order.OrderId) 234 | } 235 | //获取OrderItem 236 | var orderItems []manage.MallOrderItem 237 | if len(orderIds) > 0 { 238 | global.GVA_DB.Where("order_id in ?", orderIds).Find(&orderItems) 239 | itemByOrderIdMap := make(map[int][]manage.MallOrderItem) 240 | for _, orderItem := range orderItems { 241 | itemByOrderIdMap[orderItem.OrderId] = []manage.MallOrderItem{} 242 | } 243 | for k, v := range itemByOrderIdMap { 244 | for _, orderItem := range orderItems { 245 | if k == orderItem.OrderId { 246 | v = append(v, orderItem) 247 | } 248 | itemByOrderIdMap[k] = v 249 | } 250 | } 251 | //封装每个订单列表对象的订单项数据 252 | for _, newBeeMallOrderListVO := range orderListVOS { 253 | if _, ok := itemByOrderIdMap[newBeeMallOrderListVO.OrderId]; ok { 254 | orderItemListTemp := itemByOrderIdMap[newBeeMallOrderListVO.OrderId] 255 | var newBeeMallOrderItemVOS []mallRes.NewBeeMallOrderItemVO 256 | copier.Copy(&newBeeMallOrderItemVOS, &orderItemListTemp) 257 | newBeeMallOrderListVO.NewBeeMallOrderItemVOS = newBeeMallOrderItemVOS 258 | _, OrderStatusStr := enum.GetNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderListVO.OrderStatus) 259 | newBeeMallOrderListVO.OrderStatusString = OrderStatusStr 260 | list = append(list, newBeeMallOrderListVO) 261 | } 262 | } 263 | } 264 | } 265 | return err, list, total 266 | } 267 | -------------------------------------------------------------------------------- /service/mall/mall_shop_cart.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "errors" 5 | "github.com/jinzhu/copier" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/mall" 9 | mallReq "main.go/model/mall/request" 10 | mallRes "main.go/model/mall/response" 11 | "main.go/model/manage" 12 | "main.go/utils" 13 | "time" 14 | ) 15 | 16 | type MallShopCartService struct { 17 | } 18 | 19 | // 不分页 20 | func (m *MallShopCartService) GetMyShoppingCartItems(token string) (err error, cartItems []mallRes.CartItemResponse) { 21 | var userToken mall.MallUserToken 22 | var shopCartItems []mall.MallShoppingCartItem 23 | var goodsInfos []manage.MallGoodsInfo 24 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 25 | if err != nil { 26 | return errors.New("不存在的用户"), cartItems 27 | } 28 | global.GVA_DB.Where("user_id=? and is_deleted = 0", userToken.UserId).Find(&shopCartItems) 29 | var goodsIds []int 30 | for _, shopcartItem := range shopCartItems { 31 | goodsIds = append(goodsIds, shopcartItem.GoodsId) 32 | } 33 | global.GVA_DB.Where("goods_id in ?", goodsIds).Find(&goodsInfos) 34 | goodsMap := make(map[int]manage.MallGoodsInfo) 35 | for _, goodsInfo := range goodsInfos { 36 | goodsMap[goodsInfo.GoodsId] = goodsInfo 37 | } 38 | for _, v := range shopCartItems { 39 | var cartItem mallRes.CartItemResponse 40 | copier.Copy(&cartItem, &v) 41 | if _, ok := goodsMap[v.GoodsId]; ok { 42 | goodsInfo := goodsMap[v.GoodsId] 43 | cartItem.GoodsName = goodsInfo.GoodsName 44 | cartItem.GoodsCoverImg = goodsInfo.GoodsCoverImg 45 | cartItem.SellingPrice = goodsInfo.SellingPrice 46 | } 47 | cartItems = append(cartItems, cartItem) 48 | } 49 | 50 | return 51 | } 52 | 53 | func (m *MallShopCartService) SaveMallCartItem(token string, req mallReq.SaveCartItemParam) (err error) { 54 | if req.GoodsCount < 1 { 55 | return errors.New("商品数量不能小于 1 !") 56 | 57 | } 58 | if req.GoodsCount > 5 { 59 | return errors.New("超出单个商品的最大购买数量!") 60 | } 61 | var userToken mall.MallUserToken 62 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 63 | if err != nil { 64 | return errors.New("不存在的用户") 65 | } 66 | var shopCartItems []mall.MallShoppingCartItem 67 | // 是否已存在商品 68 | err = global.GVA_DB.Where("user_id = ? and goods_id = ? and is_deleted = 0", userToken.UserId, req.GoodsId).Find(&shopCartItems).Error 69 | if err != nil { 70 | return errors.New("已存在!无需重复添加!") 71 | } 72 | err = global.GVA_DB.Where("goods_id = ? ", req.GoodsId).First(&manage.MallGoodsInfo{}).Error 73 | if err != nil { 74 | return errors.New(" 商品为空") 75 | } 76 | var total int64 77 | global.GVA_DB.Where("user_id =? and is_deleted = 0", userToken.UserId).Count(&total) 78 | if total > 20 { 79 | return errors.New("超出购物车最大容量!") 80 | } 81 | var shopCartItem mall.MallShoppingCartItem 82 | if err = copier.Copy(&shopCartItem, &req); err != nil { 83 | return err 84 | } 85 | shopCartItem.UserId = userToken.UserId 86 | shopCartItem.CreateTime = common.JSONTime{Time: time.Now()} 87 | shopCartItem.UpdateTime = common.JSONTime{Time: time.Now()} 88 | err = global.GVA_DB.Save(&shopCartItem).Error 89 | return 90 | } 91 | 92 | func (m *MallShopCartService) UpdateMallCartItem(token string, req mallReq.UpdateCartItemParam) (err error) { 93 | //超出单个商品的最大数量 94 | if req.GoodsCount > 5 { 95 | return errors.New("超出单个商品的最大购买数量!") 96 | } 97 | var userToken mall.MallUserToken 98 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 99 | if err != nil { 100 | return errors.New("不存在的用户") 101 | } 102 | var shopCartItem mall.MallShoppingCartItem 103 | if err = global.GVA_DB.Where("cart_item_id=? and is_deleted = 0", req.CartItemId).First(&shopCartItem).Error; err != nil { 104 | return errors.New("未查询到记录!") 105 | } 106 | if shopCartItem.UserId != userToken.UserId { 107 | return errors.New("禁止该操作!") 108 | } 109 | shopCartItem.GoodsCount = req.GoodsCount 110 | shopCartItem.UpdateTime = common.JSONTime{time.Now()} 111 | err = global.GVA_DB.Save(&shopCartItem).Error 112 | return 113 | } 114 | 115 | func (m *MallShopCartService) DeleteMallCartItem(token string, id int) (err error) { 116 | var userToken mall.MallUserToken 117 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 118 | if err != nil { 119 | return errors.New("不存在的用户") 120 | } 121 | var shopCartItem mall.MallShoppingCartItem 122 | err = global.GVA_DB.Where("cart_item_id = ? and is_deleted = 0", id).First(&shopCartItem).Error 123 | if err != nil { 124 | return 125 | } 126 | if userToken.UserId != shopCartItem.UserId { 127 | return errors.New("禁止该操作!") 128 | } 129 | err = global.GVA_DB.Where("cart_item_id = ? and is_delete = 0", id).UpdateColumns(&mall.MallShoppingCartItem{IsDeleted: 1}).Error 130 | return 131 | } 132 | 133 | func (m *MallShopCartService) GetCartItemsForSettle(token string, cartItemIds []int) (err error, cartItemRes []mallRes.CartItemResponse) { 134 | var userToken mall.MallUserToken 135 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 136 | if err != nil { 137 | return errors.New("不存在的用户"), cartItemRes 138 | } 139 | var shopCartItems []mall.MallShoppingCartItem 140 | err = global.GVA_DB.Where("cart_item_id in (?) and user_id = ? and is_deleted = 0", cartItemIds, userToken.UserId).Find(&shopCartItems).Error 141 | if err != nil { 142 | return 143 | } 144 | _, cartItemRes = getMallShoppingCartItemVOS(shopCartItems) 145 | //购物车算价 146 | priceTotal := 0 147 | for _, cartItem := range cartItemRes { 148 | priceTotal = priceTotal + cartItem.GoodsCount*cartItem.SellingPrice 149 | } 150 | return 151 | } 152 | 153 | // 购物车数据转换 154 | func getMallShoppingCartItemVOS(cartItems []mall.MallShoppingCartItem) (err error, cartItemsRes []mallRes.CartItemResponse) { 155 | var goodsIds []int 156 | for _, cartItem := range cartItems { 157 | goodsIds = append(goodsIds, cartItem.GoodsId) 158 | } 159 | var newBeeMallGoods []manage.MallGoodsInfo 160 | err = global.GVA_DB.Where("goods_id in ?", goodsIds).Find(&newBeeMallGoods).Error 161 | if err != nil { 162 | return 163 | } 164 | 165 | newBeeMallGoodsMap := make(map[int]manage.MallGoodsInfo) 166 | for _, goodsInfo := range newBeeMallGoods { 167 | newBeeMallGoodsMap[goodsInfo.GoodsId] = goodsInfo 168 | } 169 | for _, cartItem := range cartItems { 170 | var cartItemRes mallRes.CartItemResponse 171 | copier.Copy(&cartItemRes, &cartItem) 172 | // 是否包含key 173 | if _, ok := newBeeMallGoodsMap[cartItemRes.GoodsId]; ok { 174 | newBeeMallGoodsTemp := newBeeMallGoodsMap[cartItemRes.GoodsId] 175 | cartItemRes.GoodsCoverImg = newBeeMallGoodsTemp.GoodsCoverImg 176 | goodsName := utils.SubStrLen(newBeeMallGoodsTemp.GoodsName, 28) 177 | cartItemRes.GoodsName = goodsName 178 | cartItemRes.SellingPrice = newBeeMallGoodsTemp.SellingPrice 179 | cartItemsRes = append(cartItemsRes, cartItemRes) 180 | } 181 | } 182 | return 183 | } 184 | -------------------------------------------------------------------------------- /service/mall/mall_user.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "errors" 5 | "github.com/jinzhu/copier" 6 | "gorm.io/gorm" 7 | "main.go/global" 8 | "main.go/model/common" 9 | "main.go/model/mall" 10 | mallReq "main.go/model/mall/request" 11 | mallRes "main.go/model/mall/response" 12 | "main.go/utils" 13 | "strconv" 14 | "strings" 15 | "time" 16 | ) 17 | 18 | type MallUserService struct { 19 | } 20 | 21 | func (m *MallUserService) RegisterUser(req mallReq.RegisterUserParam) (err error) { 22 | if !errors.Is(global.GVA_DB.Where("login_name =?", req.LoginName).First(&mall.MallUser{}).Error, gorm.ErrRecordNotFound) { 23 | return errors.New("存在相同用户名") 24 | } 25 | 26 | return global.GVA_DB.Create(&mall.MallUser{ 27 | LoginName: req.LoginName, 28 | PasswordMd5: utils.MD5V([]byte(req.Password)), 29 | IntroduceSign: "随新所欲,蜂富多彩", 30 | CreateTime: common.JSONTime{Time: time.Now()}, 31 | }).Error 32 | 33 | } 34 | 35 | func (m *MallUserService) UpdateUserInfo(token string, req mallReq.UpdateUserInfoParam) (err error) { 36 | var userToken mall.MallUserToken 37 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 38 | if err != nil { 39 | return errors.New("不存在的用户") 40 | } 41 | var userInfo mall.MallUser 42 | err = global.GVA_DB.Where("user_id =?", userToken.UserId).First(&userInfo).Error 43 | // 若密码为空字符,则表明用户不打算修改密码,使用原密码保存 44 | if !(req.PasswordMd5 == "") { 45 | userInfo.PasswordMd5 = utils.MD5V([]byte(req.PasswordMd5)) 46 | } 47 | userInfo.NickName = req.NickName 48 | userInfo.IntroduceSign = req.IntroduceSign 49 | err = global.GVA_DB.Where("user_id =?", userToken.UserId).UpdateColumns(&userInfo).Error 50 | return 51 | } 52 | 53 | func (m *MallUserService) GetUserDetail(token string) (err error, userDetail mallRes.MallUserDetailResponse) { 54 | var userToken mall.MallUserToken 55 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 56 | if err != nil { 57 | return errors.New("不存在的用户"), userDetail 58 | } 59 | var userInfo mall.MallUser 60 | err = global.GVA_DB.Where("user_id =?", userToken.UserId).First(&userInfo).Error 61 | if err != nil { 62 | return errors.New("用户信息获取失败"), userDetail 63 | } 64 | err = copier.Copy(&userDetail, &userInfo) 65 | return 66 | } 67 | 68 | func (m *MallUserService) UserLogin(params mallReq.UserLoginParam) (err error, user mall.MallUser, userToken mall.MallUserToken) { 69 | err = global.GVA_DB.Where("login_name=? AND password_md5=?", params.LoginName, params.PasswordMd5).First(&user).Error 70 | if user != (mall.MallUser{}) { 71 | token := getNewToken(time.Now().UnixNano()/1e6, int(user.UserId)) 72 | global.GVA_DB.Where("user_id", user.UserId).First(&token) 73 | nowDate := time.Now() 74 | // 48小时过期 75 | expireTime, _ := time.ParseDuration("48h") 76 | expireDate := nowDate.Add(expireTime) 77 | // 没有token新增,有token 则更新 78 | if userToken == (mall.MallUserToken{}) { 79 | userToken.UserId = user.UserId 80 | userToken.Token = token 81 | userToken.UpdateTime = nowDate 82 | userToken.ExpireTime = expireDate 83 | if err = global.GVA_DB.Save(&userToken).Error; err != nil { 84 | return 85 | } 86 | } else { 87 | userToken.Token = token 88 | userToken.UpdateTime = nowDate 89 | userToken.ExpireTime = expireDate 90 | if err = global.GVA_DB.Save(&userToken).Error; err != nil { 91 | return 92 | } 93 | } 94 | } 95 | return err, user, userToken 96 | } 97 | 98 | func getNewToken(timeInt int64, userId int) (token string) { 99 | var build strings.Builder 100 | build.WriteString(strconv.FormatInt(timeInt, 10)) 101 | build.WriteString(strconv.Itoa(userId)) 102 | build.WriteString(utils.GenValidateCode(6)) 103 | return utils.MD5V([]byte(build.String())) 104 | } 105 | -------------------------------------------------------------------------------- /service/mall/mall_user_address.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "errors" 5 | "github.com/jinzhu/copier" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/mall" 9 | mallReq "main.go/model/mall/request" 10 | "time" 11 | ) 12 | 13 | type MallUserAddressService struct { 14 | } 15 | 16 | func (m *MallUserAddressService) GetMyAddress(token string) (err error, userAddress []mall.MallUserAddress) { 17 | var userToken mall.MallUserToken 18 | err = global.GVA_DB.Where("token =?", token).First(&userToken).Error 19 | if err != nil { 20 | return errors.New("不存在的用户"), userAddress 21 | } 22 | global.GVA_DB.Where("user_id=? and is_deleted=0", userToken.UserId).Find(&userAddress) 23 | return 24 | } 25 | 26 | func (m *MallUserAddressService) SaveUserAddress(token string, req mallReq.AddAddressParam) (err error) { 27 | var userToken mall.MallUserToken 28 | if err = global.GVA_DB.Where("token =?", token).First(&userToken).Error; err != nil { 29 | return errors.New("不存在的用户") 30 | } 31 | // 是否新增了默认地址,将之前的默认地址设置为非默认 32 | var defaultAddress mall.MallUserAddress 33 | copier.Copy(&defaultAddress, &req) 34 | defaultAddress.CreateTime = common.JSONTime{Time: time.Now()} 35 | defaultAddress.UpdateTime = common.JSONTime{Time: time.Now()} 36 | defaultAddress.UserId = userToken.UserId 37 | if req.DefaultFlag == 1 { 38 | global.GVA_DB.Where("user_id=? and default_flag =1 and is_deleted = 0", userToken.UserId).First(&defaultAddress) 39 | if defaultAddress != (mall.MallUserAddress{}) { 40 | defaultAddress.UpdateTime = common.JSONTime{time.Now()} 41 | err = global.GVA_DB.Save(&defaultAddress).Error 42 | if err != nil { 43 | return 44 | } 45 | } 46 | } else { 47 | err = global.GVA_DB.Create(&defaultAddress).Error 48 | if err != nil { 49 | return 50 | } 51 | } 52 | return 53 | } 54 | 55 | func (m *MallUserAddressService) UpdateUserAddress(token string, req mallReq.UpdateAddressParam) (err error) { 56 | var userToken mall.MallUserToken 57 | if err = global.GVA_DB.Where("token =?", token).First(&userToken).Error; err != nil { 58 | return errors.New("不存在的用户") 59 | } 60 | var userAddress mall.MallUserAddress 61 | if err = global.GVA_DB.Where("address_id =? and user_id =?", req.AddressId, userToken.UserId).First(&userAddress).Error; err != nil { 62 | return errors.New("不存在的用户地址") 63 | } 64 | if userToken.UserId != userAddress.UserId { 65 | return errors.New("禁止该操作!") 66 | } 67 | if req.DefaultFlag == 1 { 68 | var defaultUserAddress mall.MallUserAddress 69 | global.GVA_DB.Where("user_id=? and default_flag =1 and is_deleted = 0", userToken.UserId).First(&defaultUserAddress) 70 | if defaultUserAddress != (mall.MallUserAddress{}) { 71 | defaultUserAddress.DefaultFlag = 0 72 | defaultUserAddress.UpdateTime = common.JSONTime{time.Now()} 73 | err = global.GVA_DB.Save(&defaultUserAddress).Error 74 | if err != nil { 75 | return 76 | } 77 | } 78 | } 79 | err = copier.Copy(&userAddress, &req) 80 | if err != nil { 81 | return 82 | } 83 | userAddress.UpdateTime = common.JSONTime{time.Now()} 84 | userAddress.UserId = userToken.UserId 85 | err = global.GVA_DB.Save(&userAddress).Error 86 | return 87 | } 88 | 89 | func (m *MallUserAddressService) GetMallUserAddressById(token string, id int) (err error, userAddress mall.MallUserAddress) { 90 | var userToken mall.MallUserToken 91 | if err = global.GVA_DB.Where("token =?", token).First(&userToken).Error; err != nil { 92 | return errors.New("不存在的用户"), userAddress 93 | } 94 | if err = global.GVA_DB.Where("address_id =?", id).First(&userAddress).Error; err != nil { 95 | return errors.New("不存在的用户地址"), userAddress 96 | } 97 | if userToken.UserId != userAddress.UserId { 98 | return errors.New("禁止该操作!"), userAddress 99 | } 100 | return 101 | } 102 | 103 | func (m *MallUserAddressService) GetMallUserDefaultAddress(token string) (err error, userAddress mall.MallUserAddress) { 104 | var userToken mall.MallUserToken 105 | if err = global.GVA_DB.Where("token =?", token).First(&userToken).Error; err != nil { 106 | return errors.New("不存在的用户"), userAddress 107 | } 108 | if err = global.GVA_DB.Where("user_id =? and default_flag =1 and is_deleted = 0 ", userToken.UserId).First(&userAddress).Error; err != nil { 109 | return errors.New("不存在默认地址失败"), userAddress 110 | } 111 | return 112 | } 113 | 114 | func (m *MallUserAddressService) DeleteUserAddress(token string, id int) (err error) { 115 | var userToken mall.MallUserToken 116 | if err = global.GVA_DB.Where("token =?", token).First(&userToken).Error; err != nil { 117 | return errors.New("不存在的用户") 118 | } 119 | var userAddress mall.MallUserAddress 120 | if err = global.GVA_DB.Where("address_id =?", id).First(&userAddress).Error; err != nil { 121 | return errors.New("不存在的用户地址") 122 | } 123 | if userToken.UserId != userAddress.UserId { 124 | return errors.New("禁止该操作!") 125 | } 126 | err = global.GVA_DB.Delete(&userAddress).Error 127 | return 128 | 129 | } 130 | -------------------------------------------------------------------------------- /service/mall/mall_user_token.go: -------------------------------------------------------------------------------- 1 | package mall 2 | 3 | import ( 4 | "main.go/global" 5 | "main.go/model/mall" 6 | ) 7 | 8 | type MallUserTokenService struct { 9 | } 10 | 11 | func (m *MallUserTokenService) ExistUserToken(token string) (err error, mallUserToken mall.MallUserToken) { 12 | err = global.GVA_DB.Where("token =?", token).First(&mallUserToken).Error 13 | return 14 | } 15 | 16 | func (m *MallUserTokenService) DeleteMallUserToken(token string) (err error) { 17 | err = global.GVA_DB.Delete(&[]mall.MallUserToken{}, "token =?", token).Error 18 | return err 19 | } 20 | -------------------------------------------------------------------------------- /service/manage/enter.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | type ManageServiceGroup struct { 4 | ManageAdminUserService 5 | ManageAdminUserTokenService 6 | ManageUserService 7 | ManageGoodsCategoryService 8 | ManageGoodsInfoService 9 | ManageCarouselService 10 | ManageIndexConfigService 11 | ManageOrderService 12 | } 13 | -------------------------------------------------------------------------------- /service/manage/manage_admin_user.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "errors" 5 | "gorm.io/gorm" 6 | "main.go/global" 7 | "main.go/model/manage" 8 | manageReq "main.go/model/manage/request" 9 | "main.go/utils" 10 | "strconv" 11 | "strings" 12 | "time" 13 | ) 14 | 15 | type ManageAdminUserService struct { 16 | } 17 | 18 | // CreateMallAdminUser 创建MallAdminUser记录 19 | func (m *ManageAdminUserService) CreateMallAdminUser(mallAdminUser manage.MallAdminUser) (err error) { 20 | if !errors.Is(global.GVA_DB.Where("login_user_name = ?", mallAdminUser.LoginUserName).First(&manage.MallAdminUser{}).Error, gorm.ErrRecordNotFound) { 21 | return errors.New("存在相同用户名") 22 | } 23 | err = global.GVA_DB.Create(&mallAdminUser).Error 24 | return err 25 | } 26 | 27 | // UpdateMallAdminName 更新MallAdminUser昵称 28 | func (m *ManageAdminUserService) UpdateMallAdminName(token string, req manageReq.MallUpdateNameParam) (err error) { 29 | var adminUserToken manage.MallAdminUserToken 30 | err = global.GVA_DB.Where("token =? ", token).First(&adminUserToken).Error 31 | if err != nil { 32 | return errors.New("不存在的用户") 33 | } 34 | err = global.GVA_DB.Where("admin_user_id = ?", adminUserToken.AdminUserId).Updates(&manage.MallAdminUser{ 35 | LoginUserName: req.LoginUserName, 36 | NickName: req.NickName, 37 | }).Error 38 | return err 39 | } 40 | 41 | func (m *ManageAdminUserService) UpdateMallAdminPassWord(token string, req manageReq.MallUpdatePasswordParam) (err error) { 42 | var adminUserToken manage.MallAdminUserToken 43 | err = global.GVA_DB.Where("token =? ", token).First(&adminUserToken).Error 44 | if err != nil { 45 | return errors.New("用户未登录") 46 | } 47 | var adminUser manage.MallAdminUser 48 | err = global.GVA_DB.Where("admin_user_id =?", adminUserToken.AdminUserId).First(&adminUser).Error 49 | if err != nil { 50 | return errors.New("不存在的用户") 51 | } 52 | if adminUser.LoginPassword != req.OriginalPassword { 53 | return errors.New("原密码不正确") 54 | } 55 | adminUser.LoginPassword = req.NewPassword 56 | 57 | err = global.GVA_DB.Where("admin_user_id=?", adminUser.AdminUserId).Updates(&adminUser).Error 58 | return 59 | } 60 | 61 | // GetMallAdminUser 根据id获取MallAdminUser记录 62 | func (m *ManageAdminUserService) GetMallAdminUser(token string) (err error, mallAdminUser manage.MallAdminUser) { 63 | var adminToken manage.MallAdminUserToken 64 | if errors.Is(global.GVA_DB.Where("token =?", token).First(&adminToken).Error, gorm.ErrRecordNotFound) { 65 | return errors.New("不存在的用户"), mallAdminUser 66 | } 67 | err = global.GVA_DB.Where("admin_user_id = ?", adminToken.AdminUserId).First(&mallAdminUser).Error 68 | return err, mallAdminUser 69 | } 70 | 71 | // AdminLogin 管理员登陆 72 | func (m *ManageAdminUserService) AdminLogin(params manageReq.MallAdminLoginParam) (err error, mallAdminUser manage.MallAdminUser, adminToken manage.MallAdminUserToken) { 73 | err = global.GVA_DB.Where("login_user_name=? AND login_password=?", params.UserName, params.PasswordMd5).First(&mallAdminUser).Error 74 | if mallAdminUser != (manage.MallAdminUser{}) { 75 | token := getNewToken(time.Now().UnixNano()/1e6, int(mallAdminUser.AdminUserId)) 76 | global.GVA_DB.Where("admin_user_id", mallAdminUser.AdminUserId).First(&adminToken) 77 | nowDate := time.Now() 78 | // 48小时过期 79 | expireTime, _ := time.ParseDuration("48h") 80 | expireDate := nowDate.Add(expireTime) 81 | // 没有token新增,有token 则更新 82 | if adminToken == (manage.MallAdminUserToken{}) { 83 | adminToken.AdminUserId = mallAdminUser.AdminUserId 84 | adminToken.Token = token 85 | adminToken.UpdateTime = nowDate 86 | adminToken.ExpireTime = expireDate 87 | if err = global.GVA_DB.Create(&adminToken).Error; err != nil { 88 | return 89 | } 90 | } else { 91 | adminToken.Token = token 92 | adminToken.UpdateTime = nowDate 93 | adminToken.ExpireTime = expireDate 94 | if err = global.GVA_DB.Save(&adminToken).Error; err != nil { 95 | return 96 | } 97 | } 98 | } 99 | return err, mallAdminUser, adminToken 100 | 101 | } 102 | 103 | func getNewToken(timeInt int64, userId int) (token string) { 104 | var build strings.Builder 105 | build.WriteString(strconv.FormatInt(timeInt, 10)) 106 | build.WriteString(strconv.Itoa(userId)) 107 | build.WriteString(utils.GenValidateCode(6)) 108 | return utils.MD5V([]byte(build.String())) 109 | } 110 | -------------------------------------------------------------------------------- /service/manage/manage_admin_user_token.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "main.go/global" 5 | "main.go/model/manage" 6 | ) 7 | 8 | type ManageAdminUserTokenService struct { 9 | } 10 | 11 | func (m *ManageAdminUserTokenService) ExistAdminToken(token string) (err error, mallAdminUserToken manage.MallAdminUserToken) { 12 | err = global.GVA_DB.Where("token =?", token).First(&mallAdminUserToken).Error 13 | return 14 | } 15 | 16 | func (m *ManageAdminUserTokenService) DeleteMallAdminUserToken(token string) (err error) { 17 | err = global.GVA_DB.Delete(&[]manage.MallAdminUserToken{}, "token =?", token).Error 18 | return err 19 | } 20 | -------------------------------------------------------------------------------- /service/manage/manage_carousel.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "errors" 5 | "gorm.io/gorm" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/common/request" 9 | "main.go/model/manage" 10 | manageReq "main.go/model/manage/request" 11 | "main.go/utils" 12 | "strconv" 13 | "time" 14 | ) 15 | 16 | type ManageCarouselService struct { 17 | } 18 | 19 | func (m *ManageCarouselService) CreateCarousel(req manageReq.MallCarouselAddParam) (err error) { 20 | carouseRank, _ := strconv.Atoi(req.CarouselRank) 21 | mallCarousel := manage.MallCarousel{ 22 | CarouselUrl: req.CarouselUrl, 23 | RedirectUrl: req.RedirectUrl, 24 | CarouselRank: carouseRank, 25 | CreateTime: common.JSONTime{Time: time.Now()}, 26 | UpdateTime: common.JSONTime{Time: time.Now()}, 27 | } 28 | // 这个校验理论上应该放在api层,但是因为前端的传值是string,而我们的校验规则是Int,所以只能转换格式后再校验 29 | if err = utils.Verify(mallCarousel, utils.CarouselAddParamVerify); err != nil { 30 | return errors.New(err.Error()) 31 | } 32 | err = global.GVA_DB.Create(&mallCarousel).Error 33 | return err 34 | } 35 | 36 | func (m *ManageCarouselService) DeleteCarousel(ids request.IdsReq) (err error) { 37 | err = global.GVA_DB.Delete(&manage.MallCarousel{}, "carousel_id in ?", ids.Ids).Error 38 | return err 39 | } 40 | 41 | func (m *ManageCarouselService) UpdateCarousel(req manageReq.MallCarouselUpdateParam) (err error) { 42 | if errors.Is(global.GVA_DB.Where("carousel_id = ?", req.CarouselId).First(&manage.MallCarousel{}).Error, gorm.ErrRecordNotFound) { 43 | return errors.New("未查询到记录!") 44 | } 45 | carouseRank, _ := strconv.Atoi(req.CarouselRank) 46 | mallCarousel := manage.MallCarousel{ 47 | CarouselUrl: req.CarouselUrl, 48 | RedirectUrl: req.RedirectUrl, 49 | CarouselRank: carouseRank, 50 | UpdateTime: common.JSONTime{Time: time.Now()}, 51 | } 52 | // 这个校验理论上应该放在api层,但是因为前端的传值是string,而我们的校验规则是Int,所以只能转换格式后再校验 53 | if err = utils.Verify(mallCarousel, utils.CarouselAddParamVerify); err != nil { 54 | return errors.New(err.Error()) 55 | } 56 | err = global.GVA_DB.Where("carousel_id = ?", req.CarouselId).UpdateColumns(&mallCarousel).Error 57 | return err 58 | } 59 | 60 | func (m *ManageCarouselService) GetCarousel(id int) (err error, mallCarousel manage.MallCarousel) { 61 | err = global.GVA_DB.Where("carousel_id = ?", id).First(&mallCarousel).Error 62 | return 63 | } 64 | 65 | func (m *ManageCarouselService) GetCarouselInfoList(info manageReq.MallCarouselSearch) (err error, list interface{}, total int64) { 66 | limit := info.PageSize 67 | offset := info.PageSize * (info.PageNumber - 1) 68 | // 创建db 69 | db := global.GVA_DB.Model(&manage.MallCarousel{}) 70 | var mallCarousels []manage.MallCarousel 71 | // 如果有条件搜索 下方会自动创建搜索语句 72 | err = db.Count(&total).Error 73 | if err != nil { 74 | return 75 | } 76 | err = db.Limit(limit).Offset(offset).Order("carousel_rank desc").Find(&mallCarousels).Error 77 | return err, mallCarousels, total 78 | } 79 | -------------------------------------------------------------------------------- /service/manage/manage_goods_category.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "errors" 5 | "gorm.io/gorm" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/common/request" 9 | "main.go/model/manage" 10 | manageReq "main.go/model/manage/request" 11 | "main.go/utils" 12 | "strconv" 13 | "time" 14 | ) 15 | 16 | type ManageGoodsCategoryService struct { 17 | } 18 | 19 | // AddCategory 添加商品分类 20 | func (m *ManageGoodsCategoryService) AddCategory(req manageReq.MallGoodsCategoryReq) (err error) { 21 | if !errors.Is(global.GVA_DB.Where("category_level=? AND category_name=? AND is_deleted=0", 22 | req.CategoryLevel, req.CategoryName).First(&manage.MallGoodsCategory{}).Error, gorm.ErrRecordNotFound) { 23 | return errors.New("存在相同分类") 24 | } 25 | rank, _ := strconv.Atoi(req.CategoryRank) 26 | category := manage.MallGoodsCategory{ 27 | CategoryLevel: req.CategoryLevel, 28 | CategoryName: req.CategoryName, 29 | CategoryRank: rank, 30 | IsDeleted: 0, 31 | CreateTime: common.JSONTime{Time: time.Now()}, 32 | UpdateTime: common.JSONTime{Time: time.Now()}, 33 | } 34 | // 这个校验理论上应该放在api层,但是因为前端的传值是string,而我们的校验规则是Int,所以只能转换格式后再校验 35 | if err = utils.Verify(category, utils.GoodsCategoryVerify); err != nil { 36 | return errors.New(err.Error()) 37 | } 38 | return global.GVA_DB.Create(&category).Error 39 | } 40 | 41 | // UpdateCategory 更新商品分类 42 | func (m *ManageGoodsCategoryService) UpdateCategory(req manageReq.MallGoodsCategoryReq) (err error) { 43 | if !errors.Is(global.GVA_DB.Where("category_level=? AND category_name=? AND is_deleted=0", 44 | req.CategoryLevel, req.CategoryName).First(&manage.MallGoodsCategory{}).Error, gorm.ErrRecordNotFound) { 45 | return errors.New("存在相同分类") 46 | } 47 | rank, _ := strconv.Atoi(req.CategoryRank) 48 | category := manage.MallGoodsCategory{ 49 | CategoryName: req.CategoryName, 50 | CategoryRank: rank, 51 | UpdateTime: common.JSONTime{Time: time.Now()}, 52 | } 53 | // 这个校验理论上应该放在api层,但是因为前端的传值是string,而我们的校验规则是Int,所以只能转换格式后再校验 54 | if err := utils.Verify(category, utils.GoodsCategoryVerify); err != nil { 55 | return errors.New(err.Error()) 56 | } 57 | return global.GVA_DB.Where("category_id =?", req.CategoryId).Updates(&category).Error 58 | 59 | } 60 | 61 | // SelectCategoryPage 获取分类分页数据 62 | func (m *ManageGoodsCategoryService) SelectCategoryPage(req manageReq.SearchCategoryParams) (err error, list interface{}, total int64) { 63 | limit := req.PageSize 64 | if limit > 1000 { 65 | limit = 1000 66 | } 67 | offset := req.PageSize * (req.PageNumber - 1) 68 | db := global.GVA_DB.Model(&manage.MallGoodsCategory{}) 69 | var categoryList []manage.MallGoodsCategory 70 | 71 | if utils.NumsInList(req.CategoryLevel, []int{1, 2, 3}) { 72 | db.Where("category_level=?", req.CategoryLevel) 73 | } 74 | if req.ParentId >= 0 { 75 | db.Where("parent_id=?", req.ParentId) 76 | } 77 | err = db.Where("is_deleted=0").Count(&total).Error 78 | 79 | if err != nil { 80 | return err, categoryList, total 81 | 82 | } else { 83 | db = db.Where("is_deleted=0").Order("category_rank desc").Limit(limit).Offset(offset) 84 | err = db.Find(&categoryList).Error 85 | } 86 | return err, categoryList, total 87 | } 88 | 89 | // SelectCategoryById 获取单个分类数据 90 | func (m *ManageGoodsCategoryService) SelectCategoryById(categoryId int) (err error, goodsCategory manage.MallGoodsCategory) { 91 | err = global.GVA_DB.Where("category_id=?", categoryId).First(&goodsCategory).Error 92 | return err, goodsCategory 93 | } 94 | 95 | // DeleteGoodsCategoriesByIds 批量设置失效 96 | func (m *ManageGoodsCategoryService) DeleteGoodsCategoriesByIds(ids request.IdsReq) (err error, goodsCategory manage.MallGoodsCategory) { 97 | err = global.GVA_DB.Where("category_id in ?", ids.Ids).UpdateColumns(manage.MallGoodsCategory{IsDeleted: 1}).Error 98 | return err, goodsCategory 99 | } 100 | 101 | func (m *ManageGoodsCategoryService) SelectByLevelAndParentIdsAndNumber(parentId int, categoryLevel int) (err error, goodsCategories []manage.MallGoodsCategory) { 102 | err = global.GVA_DB.Where("category_id in ?", parentId).Where("category_level=?", categoryLevel).Where("is_deleted=0").Error 103 | return err, goodsCategories 104 | 105 | } 106 | -------------------------------------------------------------------------------- /service/manage/manage_goods_info.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "errors" 5 | "gorm.io/gorm" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/common/enum" 9 | "main.go/model/common/request" 10 | "main.go/model/manage" 11 | manageReq "main.go/model/manage/request" 12 | "main.go/utils" 13 | "strconv" 14 | "time" 15 | ) 16 | 17 | type ManageGoodsInfoService struct { 18 | } 19 | 20 | // CreateMallGoodsInfo 创建MallGoodsInfo 21 | func (m *ManageGoodsInfoService) CreateMallGoodsInfo(req manageReq.GoodsInfoAddParam) (err error) { 22 | var goodsCategory manage.MallGoodsCategory 23 | err = global.GVA_DB.Where("category_id=? AND is_deleted=0", req.GoodsCategoryId).First(&goodsCategory).Error 24 | if goodsCategory.CategoryLevel != enum.LevelThree.Code() { 25 | return errors.New("分类数据异常") 26 | } 27 | if !errors.Is(global.GVA_DB.Where("goods_name=? AND goods_category_id=?", req.GoodsName, req.GoodsCategoryId).First(&manage.MallGoodsInfo{}).Error, gorm.ErrRecordNotFound) { 28 | return errors.New("已存在相同的商品信息") 29 | } 30 | originalPrice, _ := strconv.Atoi(req.OriginalPrice) 31 | sellingPrice, _ := strconv.Atoi(req.SellingPrice) 32 | stockNum, _ := strconv.Atoi(req.StockNum) 33 | goodsSellStatus, _ := strconv.Atoi(req.GoodsSellStatus) 34 | goodsInfo := manage.MallGoodsInfo{ 35 | GoodsName: req.GoodsName, 36 | GoodsIntro: req.GoodsIntro, 37 | GoodsCategoryId: req.GoodsCategoryId, 38 | GoodsCoverImg: req.GoodsCoverImg, 39 | GoodsDetailContent: req.GoodsDetailContent, 40 | OriginalPrice: originalPrice, 41 | SellingPrice: sellingPrice, 42 | StockNum: stockNum, 43 | Tag: req.Tag, 44 | GoodsSellStatus: goodsSellStatus, 45 | CreateTime: common.JSONTime{Time: time.Now()}, 46 | UpdateTime: common.JSONTime{Time: time.Now()}, 47 | } 48 | if err = utils.Verify(goodsInfo, utils.GoodsAddParamVerify); err != nil { 49 | return errors.New(err.Error()) 50 | } 51 | err = global.GVA_DB.Create(&goodsInfo).Error 52 | return err 53 | } 54 | 55 | // DeleteMallGoodsInfo 删除MallGoodsInfo记录 56 | func (m *ManageGoodsInfoService) DeleteMallGoodsInfo(mallGoodsInfo manage.MallGoodsInfo) (err error) { 57 | err = global.GVA_DB.Delete(&mallGoodsInfo).Error 58 | return err 59 | } 60 | 61 | // ChangeMallGoodsInfoByIds 上下架 62 | func (m *ManageGoodsInfoService) ChangeMallGoodsInfoByIds(ids request.IdsReq, sellStatus string) (err error) { 63 | intSellStatus, _ := strconv.Atoi(sellStatus) 64 | //更新字段为0时,不能直接UpdateColumns 65 | err = global.GVA_DB.Model(&manage.MallGoodsInfo{}).Where("goods_id in ?", ids.Ids).Update("goods_sell_status", intSellStatus).Error 66 | return err 67 | } 68 | 69 | // UpdateMallGoodsInfo 更新MallGoodsInfo记录 70 | func (m *ManageGoodsInfoService) UpdateMallGoodsInfo(req manageReq.GoodsInfoUpdateParam) (err error) { 71 | goodsId, _ := strconv.Atoi(req.GoodsId) 72 | originalPrice, _ := strconv.Atoi(req.OriginalPrice) 73 | stockNum, _ := strconv.Atoi(req.StockNum) 74 | goodsInfo := manage.MallGoodsInfo{ 75 | GoodsId: goodsId, 76 | GoodsName: req.GoodsName, 77 | GoodsIntro: req.GoodsIntro, 78 | GoodsCategoryId: req.GoodsCategoryId, 79 | GoodsCoverImg: req.GoodsCoverImg, 80 | GoodsDetailContent: req.GoodsDetailContent, 81 | OriginalPrice: originalPrice, 82 | SellingPrice: req.SellingPrice, 83 | StockNum: stockNum, 84 | Tag: req.Tag, 85 | GoodsSellStatus: req.GoodsSellStatus, 86 | UpdateTime: common.JSONTime{Time: time.Now()}, 87 | } 88 | if err = utils.Verify(goodsInfo, utils.GoodsAddParamVerify); err != nil { 89 | return errors.New(err.Error()) 90 | } 91 | err = global.GVA_DB.Where("goods_id=?", goodsInfo.GoodsId).Updates(&goodsInfo).Error 92 | return err 93 | } 94 | 95 | // GetMallGoodsInfo 根据id获取MallGoodsInfo记录 96 | func (m *ManageGoodsInfoService) GetMallGoodsInfo(id int) (err error, mallGoodsInfo manage.MallGoodsInfo) { 97 | err = global.GVA_DB.Where("goods_id = ?", id).First(&mallGoodsInfo).Error 98 | return 99 | } 100 | 101 | // GetMallGoodsInfoInfoList 分页获取MallGoodsInfo记录 102 | func (m *ManageGoodsInfoService) GetMallGoodsInfoInfoList(info manageReq.MallGoodsInfoSearch, goodsName string, goodsSellStatus string) (err error, list interface{}, total int64) { 103 | limit := info.PageSize 104 | offset := info.PageSize * (info.PageNumber - 1) 105 | // 创建db 106 | db := global.GVA_DB.Model(&manage.MallGoodsInfo{}) 107 | var mallGoodsInfos []manage.MallGoodsInfo 108 | // 如果有条件搜索 下方会自动创建搜索语句 109 | err = db.Count(&total).Error 110 | if err != nil { 111 | return 112 | } 113 | if goodsName != "" { 114 | db.Where("goods_name =?", goodsName) 115 | } 116 | if goodsSellStatus != "" { 117 | db.Where("goods_sell_status =?", goodsSellStatus) 118 | } 119 | err = db.Limit(limit).Offset(offset).Order("goods_id desc").Find(&mallGoodsInfos).Error 120 | return err, mallGoodsInfos, total 121 | } 122 | -------------------------------------------------------------------------------- /service/manage/manage_index_config.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "errors" 5 | "gorm.io/gorm" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/common/request" 9 | "main.go/model/manage" 10 | manageReq "main.go/model/manage/request" 11 | "main.go/utils" 12 | "strconv" 13 | "time" 14 | ) 15 | 16 | type ManageIndexConfigService struct { 17 | } 18 | 19 | // CreateMallIndexConfig 创建MallIndexConfig记录 20 | func (m *ManageIndexConfigService) CreateMallIndexConfig(req manageReq.MallIndexConfigAddParams) (err error) { 21 | var goodsInfo manage.MallGoodsInfo 22 | if errors.Is(global.GVA_DB.Where("goods_id=?", req.GoodsId).First(&goodsInfo).Error, gorm.ErrRecordNotFound) { 23 | return errors.New("商品不存在") 24 | } 25 | if errors.Is(global.GVA_DB.Where("config_type =? and goods_id=? and is_deleted=0", req.ConfigType, req.GoodsId).First(&manage.MallIndexConfig{}).Error, gorm.ErrRecordNotFound) { 26 | return errors.New("已存在相同的首页配置项") 27 | } 28 | goodsId, _ := strconv.Atoi(req.GoodsId) 29 | configRank, _ := strconv.Atoi(req.ConfigRank) 30 | mallIndexConfig := manage.MallIndexConfig{ 31 | ConfigName: req.ConfigName, 32 | ConfigType: req.ConfigType, 33 | GoodsId: goodsId, 34 | RedirectUrl: req.RedirectUrl, 35 | ConfigRank: configRank, 36 | CreateTime: common.JSONTime{Time: time.Now()}, 37 | UpdateTime: common.JSONTime{Time: time.Now()}, 38 | } 39 | if err = utils.Verify(mallIndexConfig, utils.IndexConfigAddParamVerify); err != nil { 40 | return errors.New(err.Error()) 41 | } 42 | 43 | err = global.GVA_DB.Create(&mallIndexConfig).Error 44 | return err 45 | } 46 | 47 | // DeleteMallIndexConfig 删除MallIndexConfig记录 48 | func (m *ManageIndexConfigService) DeleteMallIndexConfig(ids request.IdsReq) (err error) { 49 | err = global.GVA_DB.Where("config_id in ?", ids.Ids).Delete(&manage.MallIndexConfig{}).Error 50 | return err 51 | } 52 | 53 | // UpdateMallIndexConfig 更新MallIndexConfig记录 54 | func (m *ManageIndexConfigService) UpdateMallIndexConfig(req manageReq.MallIndexConfigUpdateParams) (err error) { 55 | //更新indexConfig 56 | if errors.Is(global.GVA_DB.Where("goods_id = ?", req.GoodsId).First(&manage.MallGoodsInfo{}).Error, gorm.ErrRecordNotFound) { 57 | return errors.New("商品不存在!") 58 | } 59 | if errors.Is(global.GVA_DB.Where("config_id=?", req.ConfigId).First(&manage.MallIndexConfig{}).Error, gorm.ErrRecordNotFound) { 60 | return errors.New("未查询到记录!") 61 | } 62 | configRank, _ := strconv.Atoi(req.ConfigRank) 63 | mallIndexConfig := manage.MallIndexConfig{ 64 | ConfigId: req.ConfigId, 65 | ConfigType: req.ConfigType, 66 | ConfigName: req.ConfigName, 67 | RedirectUrl: req.RedirectUrl, 68 | GoodsId: req.GoodsId, 69 | ConfigRank: configRank, 70 | UpdateTime: common.JSONTime{Time: time.Now()}, 71 | } 72 | if err = utils.Verify(mallIndexConfig, utils.IndexConfigUpdateParamVerify); err != nil { 73 | return errors.New(err.Error()) 74 | } 75 | var newIndexConfig manage.MallIndexConfig 76 | err = global.GVA_DB.Where("config_type=? and goods_id=?", mallIndexConfig.ConfigType, mallIndexConfig.GoodsId).First(&newIndexConfig).Error 77 | if err != nil && newIndexConfig.ConfigId == mallIndexConfig.ConfigId { 78 | return errors.New("已存在相同的首页配置项") 79 | } 80 | err = global.GVA_DB.Where("config_id=?", mallIndexConfig.ConfigId).Updates(&mallIndexConfig).Error 81 | return err 82 | } 83 | 84 | // GetMallIndexConfig 根据id获取MallIndexConfig记录 85 | func (m *ManageIndexConfigService) GetMallIndexConfig(id uint) (err error, mallIndexConfig manage.MallIndexConfig) { 86 | err = global.GVA_DB.Where("config_id = ?", id).First(&mallIndexConfig).Error 87 | return 88 | } 89 | 90 | // GetMallIndexConfigInfoList 分页获取MallIndexConfig记录 91 | func (m *ManageIndexConfigService) GetMallIndexConfigInfoList(info manageReq.MallIndexConfigSearch) (err error, list interface{}, total int64) { 92 | limit := info.PageSize 93 | offset := info.PageSize * (info.PageNumber - 1) 94 | // 创建db 95 | db := global.GVA_DB.Model(&manage.MallIndexConfig{}) 96 | // todo 有没有更好的方式实现? 97 | if utils.NumsInList(info.ConfigType, []int{1, 2, 3, 4, 5}) { 98 | db.Where("config_type=?", info.ConfigType) 99 | } 100 | var mallIndexConfigs []manage.MallIndexConfig 101 | // 如果有条件搜索 下方会自动创建搜索语句 102 | err = db.Count(&total).Error 103 | if err != nil { 104 | return 105 | } 106 | err = db.Limit(limit).Offset(offset).Order("config_rank desc").Find(&mallIndexConfigs).Error 107 | return err, mallIndexConfigs, total 108 | } 109 | -------------------------------------------------------------------------------- /service/manage/manage_order.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "errors" 5 | "github.com/jinzhu/copier" 6 | "main.go/global" 7 | "main.go/model/common" 8 | "main.go/model/common/enum" 9 | "main.go/model/common/request" 10 | "main.go/model/manage" 11 | manageRes "main.go/model/manage/response" 12 | "strconv" 13 | "time" 14 | ) 15 | 16 | type ManageOrderService struct { 17 | } 18 | 19 | // CheckDone 修改订单状态为配货成功 20 | func (m *ManageOrderService) CheckDone(ids request.IdsReq) (err error) { 21 | var orders []manage.MallOrder 22 | err = global.GVA_DB.Where("order_id in ?", ids.Ids).Find(&orders).Error 23 | var errorOrders string 24 | if len(orders) != 0 { 25 | for _, order := range orders { 26 | if order.IsDeleted == 1 { 27 | errorOrders = order.OrderNo + " " 28 | continue 29 | } 30 | if order.OrderStatus != 1 { 31 | errorOrders = order.OrderNo + " " 32 | } 33 | } 34 | if errorOrders == "" { 35 | if err := global.GVA_DB.Where("order_id in ?", ids.Ids).UpdateColumns(manage.MallOrder{OrderStatus: 2, UpdateTime: common.JSONTime{Time: time.Now()}}).Error; err != nil { 36 | return err 37 | } 38 | } else { 39 | return errors.New("订单的状态不是支付成功无法执行出库操作") 40 | } 41 | } 42 | return 43 | } 44 | 45 | // CheckOut 出库 46 | func (m *ManageOrderService) CheckOut(ids request.IdsReq) (err error) { 47 | var orders []manage.MallOrder 48 | err = global.GVA_DB.Where("order_id in ?", ids.Ids).Find(&orders).Error 49 | var errorOrders string 50 | if len(orders) != 0 { 51 | for _, order := range orders { 52 | if order.IsDeleted == 1 { 53 | errorOrders = order.OrderNo + " " 54 | continue 55 | } 56 | if order.OrderStatus != 1 && order.OrderStatus != 2 { 57 | errorOrders = order.OrderNo + " " 58 | } 59 | } 60 | if errorOrders == "" { 61 | if err := global.GVA_DB.Where("order_id in ?", ids.Ids).UpdateColumns(manage.MallOrder{OrderStatus: 3, UpdateTime: common.JSONTime{Time: time.Now()}}).Error; err != nil { 62 | return err 63 | } 64 | } else { 65 | return errors.New("订单的状态不是支付成功或配货完成无法执行出库操作") 66 | } 67 | } 68 | return 69 | } 70 | 71 | // CloseOrder 商家关闭订单 72 | func (m *ManageOrderService) CloseOrder(ids request.IdsReq) (err error) { 73 | var orders []manage.MallOrder 74 | err = global.GVA_DB.Where("order_id in ?", ids.Ids).Find(&orders).Error 75 | var errorOrders string 76 | if len(orders) != 0 { 77 | for _, order := range orders { 78 | if order.IsDeleted == 1 { 79 | errorOrders = order.OrderNo + " " 80 | continue 81 | } 82 | if order.OrderStatus == 4 || order.OrderStatus < 0 { 83 | errorOrders = order.OrderNo + " " 84 | } 85 | } 86 | if errorOrders == "" { 87 | if err := global.GVA_DB.Where("order_id in ?", ids.Ids).UpdateColumns(manage.MallOrder{OrderStatus: -3, UpdateTime: common.JSONTime{Time: time.Now()}}).Error; err != nil { 88 | return err 89 | } 90 | } else { 91 | return errors.New("订单不能执行关闭操作") 92 | } 93 | } 94 | return 95 | } 96 | 97 | // GetMallOrder 根据id获取MallOrder记录 98 | func (m *ManageOrderService) GetMallOrder(id string) (err error, newBeeMallOrderDetailVO manageRes.NewBeeMallOrderDetailVO) { 99 | var newBeeMallOrder manage.MallOrder 100 | if err = global.GVA_DB.Where("order_id = ?", id).First(&newBeeMallOrder).Error; err != nil { 101 | return 102 | } 103 | var orderItems []manage.MallOrderItem 104 | if err = global.GVA_DB.Where("order_id = ?", newBeeMallOrder.OrderId).Find(&orderItems).Error; err != nil { 105 | return 106 | } 107 | //获取订单项数据 108 | if len(orderItems) > 0 { 109 | var newBeeMallOrderItemVOS []manageRes.NewBeeMallOrderItemVO 110 | copier.Copy(&newBeeMallOrderItemVOS, &orderItems) 111 | copier.Copy(&newBeeMallOrderDetailVO, &newBeeMallOrder) 112 | 113 | _, OrderStatusStr := enum.GetNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.OrderStatus) 114 | _, payTapStr := enum.GetNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.PayType) 115 | newBeeMallOrderDetailVO.OrderStatusString = OrderStatusStr 116 | newBeeMallOrderDetailVO.PayTypeString = payTapStr 117 | newBeeMallOrderDetailVO.NewBeeMallOrderItemVOS = newBeeMallOrderItemVOS 118 | } 119 | return 120 | } 121 | 122 | // GetMallOrderInfoList 分页获取MallOrder记录 123 | func (m *ManageOrderService) GetMallOrderInfoList(info request.PageInfo, orderNo string, orderStatus string) (err error, list interface{}, total int64) { 124 | limit := info.PageSize 125 | offset := info.PageSize * (info.PageNumber - 1) 126 | // 创建db 127 | db := global.GVA_DB.Model(&manage.MallOrder{}) 128 | if orderNo != "" { 129 | db.Where("order_no", orderNo) 130 | } 131 | // 0.待支付 1.已支付 2.配货完成 3:出库成功 4.交易成功 -1.手动关闭 -2.超时关闭 -3.商家关闭 132 | if orderStatus != "" { 133 | status, _ := strconv.Atoi(orderStatus) 134 | db.Where("order_status", status) 135 | } 136 | var mallOrders []manage.MallOrder 137 | // 如果有条件搜索 下方会自动创建搜索语句 138 | err = db.Count(&total).Error 139 | if err != nil { 140 | return 141 | } 142 | err = db.Limit(limit).Offset(offset).Order("update_time desc").Find(&mallOrders).Error 143 | return err, mallOrders, total 144 | } 145 | -------------------------------------------------------------------------------- /service/manage/manage_user.go: -------------------------------------------------------------------------------- 1 | package manage 2 | 3 | import ( 4 | "errors" 5 | "main.go/global" 6 | "main.go/model/common/request" 7 | "main.go/model/manage" 8 | manageReq "main.go/model/manage/request" 9 | ) 10 | 11 | type ManageUserService struct { 12 | } 13 | 14 | // LockUser 修改用户状态 15 | func (m *ManageUserService) LockUser(idReq request.IdsReq, lockStatus int) (err error) { 16 | if lockStatus != 0 && lockStatus != 1 { 17 | return errors.New("操作非法!") 18 | } 19 | //更新字段为0时,不能直接UpdateColumns 20 | err = global.GVA_DB.Model(&manage.MallUser{}).Where("user_id in ?", idReq.Ids).Update("locked_flag", lockStatus).Error 21 | return err 22 | } 23 | 24 | // GetMallUserInfoList 分页获取商城注册用户列表 25 | func (m *ManageUserService) GetMallUserInfoList(info manageReq.MallUserSearch) (err error, list interface{}, total int64) { 26 | limit := info.PageSize 27 | offset := info.PageSize * (info.PageNumber - 1) 28 | // 创建db 29 | db := global.GVA_DB.Model(&manage.MallUser{}) 30 | var mallUsers []manage.MallUser 31 | // 如果有条件搜索 下方会自动创建搜索语句 32 | err = db.Count(&total).Error 33 | if err != nil { 34 | return 35 | } 36 | err = db.Limit(limit).Offset(offset).Order("create_time desc").Find(&mallUsers).Error 37 | return err, mallUsers, total 38 | } 39 | -------------------------------------------------------------------------------- /static-files/newbee-mall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/newbee-mall.png -------------------------------------------------------------------------------- /static-files/商品搜索.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/商品搜索.png -------------------------------------------------------------------------------- /static-files/地址管理.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/地址管理.png -------------------------------------------------------------------------------- /static-files/生成订单.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/生成订单.png -------------------------------------------------------------------------------- /static-files/登录.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/登录.png -------------------------------------------------------------------------------- /static-files/订单列表.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/订单列表.png -------------------------------------------------------------------------------- /static-files/订单详情.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/订单详情.png -------------------------------------------------------------------------------- /static-files/详情页.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/详情页.png -------------------------------------------------------------------------------- /static-files/购物车.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/购物车.png -------------------------------------------------------------------------------- /static-files/项目结构说明.md: -------------------------------------------------------------------------------- 1 | ### 目录说明 2 | 3 | mall包下存放的前台相关业务逻辑 4 | 5 | manage 包下存放的是后管相关业务逻辑 6 | 7 | 8 | | 文件夹 | 说明 | 描述 | 9 | | ------------ | ----------------------- | --------------------------- | 10 | | `api` | api层 | api层 | 11 | | `--v1` | v1版本接口 | v1版本接口 | 12 | | `config` | 配置包 | config.yaml对应的配置结构体 | 13 | | `core` | 核心文件 | 核心组件(zap, viper, server)的初始化 | 14 | | `global` | 全局对象 | 全局对象 | 15 | | `initialize` | 初始化 | router,redis,gorm,validator, timer的初始化 | 16 | | `--internal` | 初始化内部函数 | gorm 的 longger 自定义,在此文件夹的函数只能由 `initialize` 层进行调用 | 17 | | `middleware` | 中间件层 | 用于存放 `gin` 中间件代码 | 18 | | `model` | 模型层 | 模型对应数据表 | 19 | | `router` | 路由层 | 路由层 | 20 | | `service` | service层 | 存放业务逻辑问题 | 21 | | `utils` | 工具包 | 工具函数封装 | 22 | -------------------------------------------------------------------------------- /static-files/首页.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalaohekele/newbee-mall-api-go/3eb60e124b63b70d029bd4ebb4a4c36a257ff1c3/static-files/首页.png -------------------------------------------------------------------------------- /utils/constant.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | const ( 4 | ConfigEnv = "GVA_CONFIG" 5 | ConfigFile = "config.yaml" 6 | ) 7 | -------------------------------------------------------------------------------- /utils/directory.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "go.uber.org/zap" 5 | "main.go/global" 6 | "os" 7 | ) 8 | 9 | //@author: [piexlmax](https://github.com/piexlmax) 10 | //@function: PathExists 11 | //@description: 文件目录是否存在 12 | //@param: path string 13 | //@return: bool, error 14 | 15 | func PathExists(path string) (bool, error) { 16 | _, err := os.Stat(path) 17 | if err == nil { 18 | return true, nil 19 | } 20 | if os.IsNotExist(err) { 21 | return false, nil 22 | } 23 | return false, err 24 | } 25 | 26 | //@author: [piexlmax](https://github.com/piexlmax) 27 | //@function: CreateDir 28 | //@description: 批量创建文件夹 29 | //@param: dirs ...string 30 | //@return: err error 31 | 32 | func CreateDir(dirs ...string) (err error) { 33 | for _, v := range dirs { 34 | exist, err := PathExists(v) 35 | if err != nil { 36 | return err 37 | } 38 | if !exist { 39 | global.GVA_LOG.Debug("create directory" + v) 40 | if err := os.MkdirAll(v, os.ModePerm); err != nil { 41 | global.GVA_LOG.Error("create directory"+v, zap.Any(" error:", err)) 42 | return err 43 | } 44 | } 45 | } 46 | return err 47 | } 48 | -------------------------------------------------------------------------------- /utils/md5.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/md5" 5 | "encoding/hex" 6 | ) 7 | 8 | //@author: [piexlmax](https://github.com/piexlmax) 9 | //@function: MD5V 10 | //@description: md5加密 11 | //@param: str []byte 12 | //@return: string 13 | 14 | func MD5V(str []byte, b ...byte) string { 15 | h := md5.New() 16 | h.Write(str) 17 | return hex.EncodeToString(h.Sum(b)) 18 | } 19 | -------------------------------------------------------------------------------- /utils/nums_utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "strconv" 7 | "strings" 8 | "time" 9 | ) 10 | 11 | // NumsInList 数值是否存在 12 | func NumsInList(num int, nums []int) bool { 13 | for _, s := range nums { 14 | if s == num { 15 | return true 16 | } 17 | } 18 | return false 19 | } 20 | 21 | // GenValidateCode 随机6位数 22 | func GenValidateCode(width int) string { 23 | numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 24 | r := len(numeric) 25 | rand.Seed(time.Now().UnixNano()) 26 | 27 | var sb strings.Builder 28 | for i := 0; i < width; i++ { 29 | _, err := fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)]) 30 | if err != nil { 31 | return "" 32 | } 33 | } 34 | return sb.String() 35 | } 36 | 37 | func GenOrderNo() string { 38 | numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 39 | r := len(numeric) 40 | rand.Seed(time.Now().UnixNano()) 41 | 42 | var sb strings.Builder 43 | for i := 0; i < 4; i++ { 44 | _, err := fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)]) 45 | if err != nil { 46 | return "" 47 | } 48 | } 49 | timestamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10) 50 | return timestamp + sb.String() 51 | } 52 | 53 | // '2,3' 转换为[2,3] 54 | func StrToInt(strNum string) (nums []int) { 55 | strNums := strings.Split(strNum, ",") 56 | for _, s := range strNums { 57 | i, _ := strconv.Atoi(s) 58 | nums = append(nums, i) 59 | } 60 | return 61 | } 62 | -------------------------------------------------------------------------------- /utils/rotatelogs.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/natefinch/lumberjack" 5 | "go.uber.org/zap/zapcore" 6 | "main.go/global" 7 | "os" 8 | ) 9 | 10 | //@author: [SliverHorn](https://github.com/SliverHorn) 11 | //@function: GetWriteSyncer 12 | //@description: zap logger中加入file-rotatelogs 13 | //@return: zapcore.WriteSyncer, error 14 | 15 | func GetWriteSyncer(file string) zapcore.WriteSyncer { 16 | lumberJackLogger := &lumberjack.Logger{ 17 | Filename: file, //日志文件的位置 18 | MaxSize: 10, //在进行切割之前,日志文件的最大大小(以MB为单位) 19 | MaxBackups: 200, //保留旧文件的最大个数 20 | MaxAge: 30, //保留旧文件的最大天数 21 | Compress: true, //是否压缩/归档旧文件 22 | } 23 | 24 | if global.GVA_CONFIG.Zap.LogInConsole { 25 | return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(lumberJackLogger)) 26 | } 27 | return zapcore.AddSync(lumberJackLogger) 28 | } 29 | -------------------------------------------------------------------------------- /utils/str_utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "fmt" 4 | 5 | func SubStrLen(str string, length int) string { 6 | nameRune := []rune(str) 7 | fmt.Println("string(nameRune[:4]) = ", string(nameRune[:4])) 8 | if len(str) > length { 9 | return string(nameRune[:length-1]) + "..." 10 | } 11 | return string(nameRune) 12 | } 13 | -------------------------------------------------------------------------------- /utils/upload/local.go: -------------------------------------------------------------------------------- 1 | package upload 2 | 3 | import ( 4 | "errors" 5 | "go.uber.org/zap" 6 | "io" 7 | "main.go/global" 8 | "main.go/utils" 9 | "mime/multipart" 10 | "os" 11 | "path" 12 | "strings" 13 | "time" 14 | ) 15 | 16 | type Local struct{} 17 | 18 | func (*Local) UploadFile(file *multipart.FileHeader) (string, string, error) { 19 | // 读取文件后缀 20 | ext := path.Ext(file.Filename) 21 | // 读取文件名并加密 22 | name := strings.TrimSuffix(file.Filename, ext) 23 | name = utils.MD5V([]byte(name)) 24 | // 拼接新文件名 25 | filename := name + "_" + time.Now().Format("20060102150405") + ext 26 | // 尝试创建此路径 27 | mkdirErr := os.MkdirAll(global.GVA_CONFIG.Local.Path, os.ModePerm) 28 | if mkdirErr != nil { 29 | global.GVA_LOG.Error("function os.MkdirAll() Filed", zap.Any("err", mkdirErr.Error())) 30 | return "", "", errors.New("function os.MkdirAll() Filed, err:" + mkdirErr.Error()) 31 | } 32 | // 拼接路径和文件名 33 | p := global.GVA_CONFIG.Local.Path + "/" + filename 34 | 35 | f, openError := file.Open() // 读取文件 36 | if openError != nil { 37 | global.GVA_LOG.Error("function file.Open() Filed", zap.Any("err", openError.Error())) 38 | return "", "", errors.New("function file.Open() Filed, err:" + openError.Error()) 39 | } 40 | defer f.Close() // 创建文件 defer 关闭 41 | 42 | out, createErr := os.Create(p) 43 | if createErr != nil { 44 | global.GVA_LOG.Error("function os.Create() Filed", zap.Any("err", createErr.Error())) 45 | 46 | return "", "", errors.New("function os.Create() Filed, err:" + createErr.Error()) 47 | } 48 | defer out.Close() // 创建文件 defer 关闭 49 | 50 | _, copyErr := io.Copy(out, f) // 传输(拷贝)文件 51 | if copyErr != nil { 52 | global.GVA_LOG.Error("function io.Copy() Filed", zap.Any("err", copyErr.Error())) 53 | return "", "", errors.New("function io.Copy() Filed, err:" + copyErr.Error()) 54 | } 55 | return p, filename, nil 56 | } 57 | 58 | //@author: [piexlmax](https://github.com/piexlmax) 59 | //@author: [ccfish86](https://github.com/ccfish86) 60 | //@author: [SliverHorn](https://github.com/SliverHorn) 61 | //@object: *Local 62 | //@function: DeleteFile 63 | //@description: 删除文件 64 | //@param: key string 65 | //@return: error 66 | 67 | func (*Local) DeleteFile(key string) error { 68 | p := global.GVA_CONFIG.Local.Path + "/" + key 69 | if strings.Contains(p, global.GVA_CONFIG.Local.Path) { 70 | if err := os.Remove(p); err != nil { 71 | return errors.New("本地文件删除失败, err:" + err.Error()) 72 | } 73 | } 74 | return nil 75 | } 76 | -------------------------------------------------------------------------------- /utils/upload/upload.go: -------------------------------------------------------------------------------- 1 | package upload 2 | 3 | import ( 4 | "main.go/global" 5 | "mime/multipart" 6 | ) 7 | 8 | type OSS interface { 9 | UploadFile(file *multipart.FileHeader) (string, string, error) 10 | DeleteFile(key string) error 11 | } 12 | 13 | //@author: [ccfish86](https://github.com/ccfish86) 14 | //@author: [SliverHorn](https://github.com/SliverHorn) 15 | //@function: NewOss 16 | //@description: OSS接口 17 | //@description: OSS的实例化方法 18 | //@return: OSS 19 | 20 | func NewOss() OSS { 21 | switch global.GVA_CONFIG.System.OssType { 22 | case "local": 23 | return &Local{} 24 | default: 25 | return &Local{} 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /utils/validator.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "errors" 5 | "reflect" 6 | "regexp" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | type Rules map[string][]string 12 | 13 | type RulesMap map[string]Rules 14 | 15 | var CustomizeMap = make(map[string]Rules) 16 | 17 | //@author: [piexlmax](https://github.com/piexlmax) 18 | //@function: RegisterRule 19 | //@description: 注册自定义规则方案建议在路由初始化层即注册 20 | //@param: key string, rule Rules 21 | //@return: err error 22 | 23 | func RegisterRule(key string, rule Rules) (err error) { 24 | if CustomizeMap[key] != nil { 25 | return errors.New(key + "已注册,无法重复注册") 26 | } else { 27 | CustomizeMap[key] = rule 28 | return nil 29 | } 30 | } 31 | 32 | //@author: [piexlmax](https://github.com/piexlmax) 33 | //@function: NotEmpty 34 | //@description: 非空 不能为其对应类型的0值 35 | //@return: string 36 | 37 | func NotEmpty() string { 38 | return "notEmpty" 39 | } 40 | 41 | //@author: [zooqkl](https://github.com/zooqkl) 42 | //@function: RegexpMatch 43 | //@description: 正则校验 校验输入项是否满足正则表达式 44 | //@param: rule string 45 | //@return: string 46 | func RegexpMatch(rule string) string { 47 | return "regexp=" + rule 48 | } 49 | 50 | //@author: [piexlmax](https://github.com/piexlmax) 51 | //@function: Lt 52 | //@description: 小于入参(<) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较 53 | //@param: mark string 54 | //@return: string 55 | 56 | func Lt(mark string) string { 57 | return "lt=" + mark 58 | } 59 | 60 | //@author: [piexlmax](https://github.com/piexlmax) 61 | //@function: Le 62 | //@description: 小于等于入参(<=) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较 63 | //@param: mark string 64 | //@return: string 65 | 66 | func Le(mark string) string { 67 | return "le=" + mark 68 | } 69 | 70 | //@author: [piexlmax](https://github.com/piexlmax) 71 | //@function: Eq 72 | //@description: 等于入参(==) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较 73 | //@param: mark string 74 | //@return: string 75 | 76 | func Eq(mark string) string { 77 | return "eq=" + mark 78 | } 79 | 80 | //@author: [piexlmax](https://github.com/piexlmax) 81 | //@function: Ne 82 | //@description: 不等于入参(!=) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较 83 | //@param: mark string 84 | //@return: string 85 | 86 | func Ne(mark string) string { 87 | return "ne=" + mark 88 | } 89 | 90 | //@author: [piexlmax](https://github.com/piexlmax) 91 | //@function: Ge 92 | //@description: 大于等于入参(>=) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较 93 | //@param: mark string 94 | //@return: string 95 | 96 | func Ge(mark string) string { 97 | return "ge=" + mark 98 | } 99 | 100 | //@author: [piexlmax](https://github.com/piexlmax) 101 | //@function: Gt 102 | //@description: 大于入参(>) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较 103 | //@param: mark string 104 | //@return: string 105 | 106 | func Gt(mark string) string { 107 | return "gt=" + mark 108 | } 109 | 110 | // 111 | //@author: [piexlmax](https://github.com/piexlmax) 112 | //@function: Verify 113 | //@description: 校验方法 114 | //@param: st interface{}, roleMap Rules(入参实例,规则map) 115 | //@return: err error 116 | 117 | func Verify(st interface{}, roleMap Rules) (err error) { 118 | compareMap := map[string]bool{ 119 | "lt": true, 120 | "le": true, 121 | "eq": true, 122 | "ne": true, 123 | "ge": true, 124 | "gt": true, 125 | } 126 | 127 | typ := reflect.TypeOf(st) 128 | val := reflect.ValueOf(st) // 获取reflect.Type类型 129 | 130 | kd := val.Kind() // 获取到st对应的类别 131 | if kd != reflect.Struct { 132 | return errors.New("expect struct") 133 | } 134 | num := val.NumField() 135 | // 遍历结构体的所有字段 136 | for i := 0; i < num; i++ { 137 | tagVal := typ.Field(i) 138 | val := val.Field(i) 139 | if len(roleMap[tagVal.Name]) > 0 { 140 | for _, v := range roleMap[tagVal.Name] { 141 | switch { 142 | case v == "notEmpty": 143 | if isBlank(val) { 144 | return errors.New(tagVal.Name + "值不能为空") 145 | } 146 | case strings.Split(v, "=")[0] == "regexp": 147 | if !regexpMatch(strings.Split(v, "=")[1], val.String()) { 148 | return errors.New(tagVal.Name + "格式校验不通过") 149 | } 150 | case compareMap[strings.Split(v, "=")[0]]: 151 | if !compareVerify(val, v) { 152 | return errors.New(tagVal.Name + "长度或值不在合法范围," + v) 153 | } 154 | } 155 | } 156 | } 157 | } 158 | return nil 159 | } 160 | 161 | //@author: [piexlmax](https://github.com/piexlmax) 162 | //@function: compareVerify 163 | //@description: 长度和数字的校验方法 根据类型自动校验 164 | //@param: value reflect.Value, VerifyStr string 165 | //@return: bool 166 | 167 | func compareVerify(value reflect.Value, VerifyStr string) bool { 168 | switch value.Kind() { 169 | case reflect.String, reflect.Slice, reflect.Array: 170 | return compare(value.Len(), VerifyStr) 171 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 172 | return compare(value.Uint(), VerifyStr) 173 | case reflect.Float32, reflect.Float64: 174 | return compare(value.Float(), VerifyStr) 175 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 176 | return compare(value.Int(), VerifyStr) 177 | default: 178 | return false 179 | } 180 | } 181 | 182 | //@author: [piexlmax](https://github.com/piexlmax) 183 | //@function: isBlank 184 | //@description: 非空校验 185 | //@param: value reflect.Value 186 | //@return: bool 187 | 188 | func isBlank(value reflect.Value) bool { 189 | switch value.Kind() { 190 | case reflect.String: 191 | return value.Len() == 0 192 | case reflect.Bool: 193 | return !value.Bool() 194 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 195 | return value.Int() == 0 196 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 197 | return value.Uint() == 0 198 | case reflect.Float32, reflect.Float64: 199 | return value.Float() == 0 200 | case reflect.Interface, reflect.Ptr: 201 | return value.IsNil() 202 | } 203 | return reflect.DeepEqual(value.Interface(), reflect.Zero(value.Type()).Interface()) 204 | } 205 | 206 | //@author: [piexlmax](https://github.com/piexlmax) 207 | //@function: compare 208 | //@description: 比较函数 209 | //@param: value interface{}, VerifyStr string 210 | //@return: bool 211 | 212 | func compare(value interface{}, VerifyStr string) bool { 213 | VerifyStrArr := strings.Split(VerifyStr, "=") 214 | val := reflect.ValueOf(value) 215 | switch val.Kind() { 216 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 217 | VInt, VErr := strconv.ParseInt(VerifyStrArr[1], 10, 64) 218 | if VErr != nil { 219 | return false 220 | } 221 | switch { 222 | case VerifyStrArr[0] == "lt": 223 | return val.Int() < VInt 224 | case VerifyStrArr[0] == "le": 225 | return val.Int() <= VInt 226 | case VerifyStrArr[0] == "eq": 227 | return val.Int() == VInt 228 | case VerifyStrArr[0] == "ne": 229 | return val.Int() != VInt 230 | case VerifyStrArr[0] == "ge": 231 | return val.Int() >= VInt 232 | case VerifyStrArr[0] == "gt": 233 | return val.Int() > VInt 234 | default: 235 | return false 236 | } 237 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 238 | VInt, VErr := strconv.Atoi(VerifyStrArr[1]) 239 | if VErr != nil { 240 | return false 241 | } 242 | switch { 243 | case VerifyStrArr[0] == "lt": 244 | return val.Uint() < uint64(VInt) 245 | case VerifyStrArr[0] == "le": 246 | return val.Uint() <= uint64(VInt) 247 | case VerifyStrArr[0] == "eq": 248 | return val.Uint() == uint64(VInt) 249 | case VerifyStrArr[0] == "ne": 250 | return val.Uint() != uint64(VInt) 251 | case VerifyStrArr[0] == "ge": 252 | return val.Uint() >= uint64(VInt) 253 | case VerifyStrArr[0] == "gt": 254 | return val.Uint() > uint64(VInt) 255 | default: 256 | return false 257 | } 258 | case reflect.Float32, reflect.Float64: 259 | VFloat, VErr := strconv.ParseFloat(VerifyStrArr[1], 64) 260 | if VErr != nil { 261 | return false 262 | } 263 | switch { 264 | case VerifyStrArr[0] == "lt": 265 | return val.Float() < VFloat 266 | case VerifyStrArr[0] == "le": 267 | return val.Float() <= VFloat 268 | case VerifyStrArr[0] == "eq": 269 | return val.Float() == VFloat 270 | case VerifyStrArr[0] == "ne": 271 | return val.Float() != VFloat 272 | case VerifyStrArr[0] == "ge": 273 | return val.Float() >= VFloat 274 | case VerifyStrArr[0] == "gt": 275 | return val.Float() > VFloat 276 | default: 277 | return false 278 | } 279 | default: 280 | return false 281 | } 282 | } 283 | 284 | func regexpMatch(rule, matchStr string) bool { 285 | return regexp.MustCompile(rule).MatchString(matchStr) 286 | } 287 | -------------------------------------------------------------------------------- /utils/verify.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | var ( 4 | GoodsCategoryVerify = Rules{"CategoryRank": {NotEmpty()}, "CategoryName": {NotEmpty()}} 5 | AdminUserRegisterVerify = Rules{"Username": {NotEmpty()}, "NickName": {NotEmpty()}, "Password": {NotEmpty()}} 6 | MallUserRegisterVerify = Rules{"Username": {NotEmpty()}, "Password": {NotEmpty()}} 7 | AdminUserChangePasswordVerify = Rules{"Password": {NotEmpty()}} 8 | GoodsAddParamVerify = Rules{"GoodsName": {Le("128")}, "GoodsIntro": {Le("200")}, "GoodsCategoryId": {Ge("1")}, "GoodsCoverImg": {NotEmpty()}, "OriginalPrice": {Ge("1"), Le("1000000")}, 9 | "sellingPrice": {Ge("1"), Le("1000000")}, "stockNum": {Ge("1"), Le("100000")}, "Tag": {Le("16")}, "goodsDetailContent": {NotEmpty()}} 10 | CarouselAddParamVerify = Rules{"CarouselUrl": {NotEmpty()}, "RedirectUrl": {NotEmpty()}, "CarouselRank": {NotEmpty(), Ge("0"), Le("200")}} 11 | IndexConfigAddParamVerify = Rules{"ConfigName": {NotEmpty()}, "ConfigType": {Ge("1"), Le("5")}, "GoodsId": {NotEmpty()}, "ConfigRank": {Ge("1"), Le("200")}} 12 | IndexConfigUpdateParamVerify = Rules{"ConfigId": {NotEmpty()}, "ConfigName": {NotEmpty()}, "ConfigType": {Ge("1"), Le("5")}, "GoodsId": {NotEmpty()}, "ConfigRank": {Ge("1"), Le("200")}} 13 | SaveOrderParamVerify = Rules{"CartItemIds": {NotEmpty()}, "AddressId": {NotEmpty()}} 14 | ) 15 | --------------------------------------------------------------------------------