一、快速启动order_web项目
- 将之前的goods_web项目的文件拷贝到order_web目录下
- 选择路径 D:\GOProject\mxshop_srvs\mxshop_api\order_web 替换:将 goods_web 全部替换为 order_web
- 添加 order_web 的 nacos配置
{
"host": "192.168.78.1",
"name": "order_web",
"port": 8083,
"tags": ["mxshop","imooc","bobby","order","web"],
"goods_srv": {
"name": "goods_srv"
},
"order_srv": {
"name": "order_srv"
},
"jwt": {
"key": "VYLDYq3&hGWjWqF$K1ih"
},
"consul": {
"host": "192.168.78.131",
"port": 8500
}
}
- 修改api、router、proto:具体的查看源码
二、购物车api接口
1 - 测试中间件
- order_web/middlewares/test_set_userid.go:这里为了测试效率去掉了jwt的验证,并且直接指定userId = 1 来进行接口测试
package middlewares
import (
"github.com/gin-gonic/gin"
)
func SetUserId() gin.HandlerFunc {
return func(ctx *gin.Context) {
var userId uint = 1
ctx.Set("userId", userId)
ctx.Next()
}
}
- order_web/router/router_shop_cart.go:添加设置userId的中间件
package router
import (
"github.com/gin-gonic/gin"
"web_api/order_web/api/shop_cart"
"web_api/order_web/middlewares"
)
func InitShopCartRouter(Router *gin.RouterGroup) {
ShopCartRouter := Router.Group("shopcarts").Use(middlewares.SetUserId())
{
ShopCartRouter.GET("", shop_cart.List)
ShopCartRouter.DELETE("/:id", shop_cart.Delete)
ShopCartRouter.POST("", shop_cart.New)
ShopCartRouter.PATCH("/:id", shop_cart.Update)
}
}
2 - 订单列表接口
- order_web/api/shop_cart/api_shop_cart.go:
func List(ctx *gin.Context) {
userId, _ := ctx.Get("userId")
fmt.Println(userId)
rsp, err := global.OrderSrvClient.CartItemList(context.Background(), &proto.UserInfo{
Id: int32(userId.(uint)),
})
if err != nil {
zap.S().Errorw("[List] 查询 【购物车列表】失败")
api.HandleGrpcErrorToHttp(err, ctx)
return
}
ids := make([]int32, 0)
for _, item := range rsp.Data {
ids = append(ids, item.GoodsId)
}
if len(ids) == 0 {
ctx.JSON(http.StatusOK, gin.H{
"total": 0,
})
return
}
goodsRsp, err := global.GoodsSrvClient.BatchGetGoods(context.Background(), &proto.BatchGoodsIdInfo{
Id: ids,
})
if err != nil {
zap.S(