Golang项目实战--GRPC示例「用户相关接口的调用」

关于grpc的部分,可以参考http://www.siyueweb.cn/go%E8%AF%AD%E8%A8%80/gRPC%E7%AE%80%E4%BB%8B.html

在这里,用一个查询用户列表的接口来举例,下面的代码实现了返回用户列表信息的结果:

func GetUserList(ctx *gin.Context) {
	ip := "127.0.0.1"
	port := 8088
	userConn, err := grpc.Dial(fmt.Sprintf("%s:%d", ip, port), grpc.WithInsecure())
	if err != nil {
		zap.S().Errorw("[GetUserList] 链接用户服务失败", "msg", err.Error())
	}
	userSrvClient := proto.NewUserClient(userConn)
	pn := ctx.DefaultQuery("pn", "0")
	pnInt, _ := strconv.Atoi(pn)
	pSize := ctx.DefaultQuery("psize", "10")
	pSizeInt, _ := strconv.Atoi(pSize)
	rsp, err := userSrvClient.GetUserList(context.Background(), &proto.PageInfo{
		Pn:    uint32(pnInt),
		PSize: uint32(pSizeInt),
	})
	if err != nil {
		zap.S().Errorw("[GetUserList] 查询用户列表失败")
		HandleGrpcErrorToHttp(err, ctx)
		return
	}
	result := make([]interface{}, 0)
	for _, value := range rsp.Data {
		//data := make(map[string]interface{})
		user := response.UserResponse{
			Id:       value.Id,
			NickName: value.NickName,
			BirthDay: response.JsonTime(time.Unix(int64(value.BirthDay), 0)),
			Gender:   value.Gender,
			Mobile:   value.Mobile,
		}

		//data["id"] = value.Id
		//data["name"] = value.NickName
		//data["birthday"] = value.BirthDay
		//data["gender"] = value.Gender
		//data["mobile"] = value.Mobile
		result = append(result, user)
	}
	ctx.JSON(http.StatusOK, result)

}

然后,返回的数据如下:

[
    {
        "id": 1,
        "nickName": "kol0",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339480"
    },
    {
        "id": 2,
        "nickName": "kol1",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339481"
    },
    {
        "id": 3,
        "nickName": "kol2",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339482"
    },
    {
        "id": 4,
        "nickName": "kol3",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339483"
    },
    {
        "id": 5,
        "nickName": "kol4",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339484"
    },
    {
        "id": 6,
        "nickName": "kol5",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339485"
    },
    {
        "id": 7,
        "nickName": "kol6",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339486"
    },
    {
        "id": 8,
        "nickName": "kol7",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339487"
    },
    {
        "id": 9,
        "nickName": "kol8",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339488"
    },
    {
        "id": 10,
        "nickName": "kol9",
        "birthDay": "1970-01-01",
        "gender": "male",
        "mobile": "13234339489"
    }
]

 

posted @ 2023-05-13 19:25  99号的格调  阅读(89)  评论(0编辑  收藏  举报