go-web 项目笔记(2) 用户模块实现思路
2.实现GetUserList-api
-
生成proto文件
# proto 文件生成命令 py: python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. user.proto go: protoc -I . goods.proto --go_out=plugins=grpc:. -
首先建立rpc连接
// 1.创建一个连接 conn, err := grpc.Dial(ip+":"+port, grpc.WithInsecure()) if err != nil { zap.S().Errorw("创建grpc连接 【用户服务失败】,", "msg", err.Error()) } // 2.创建一个proto 中用户服务的客户端 client := proto.NewUserClient(conn) -
请求server接口,得到返回数据
// 3.像底层服务发送请求,得到响应数据,还是protobuf 格式的数据信息 PageInfoReq := &proto.PageInfo{Pn: 1, PSize: 2} rsp, err := client.GetUserList(context.Background(), PageInfoReq) -
对数据做处理 proto 返回的数据信息 转换为json 返回给前端
-
grpc中code码转换为http状态码
//将grpc的code转换成http的状态码 func HandleGrpcErrorToHttp(err error, c *gin.Context) { if err != nil { if e, ok := status.FromError(err); ok { switch e.Code() { case codes.NotFound: c.JSON(http.StatusNotFound, gin.H{ "msg": e.Message(), }) case codes.Internal: c.JSON(http.StatusInternalServerError, gin.H{ "msg:": "内部错误", }) case codes.InvalidArgument: c.JSON(http.StatusBadRequest, gin.H{ "msg": "参数错误", }) case codes.Unavailable: c.JSON(http.StatusInternalServerError, gin.H{ "msg": "用户服务不可用", }) default: c.JSON(http.StatusInternalServerError, gin.H{ "msg": e.Code(), }) } return } } } // 4.这里处理grpc的处理 转化为 http 的错误码 if err != nil { zap.S().Errorw("【GetUserList】查询 【用户列表】失败") HandleGrpcErrorToHttp(err, c) return } -
proto 信息转换为json数据
/*针对proto 返回的数据信息 做转换*/ type JsonTime time.Time func (j JsonTime) MarshalJSON() ([]byte, error) { var stmp = fmt.Sprintf("\"%s\"", time.Time(j).Format("2006-01-02")) return []byte(stmp), nil } type UserResponse struct { Id int32 `json:"id"` NickName string `json:"name"` //Birthday string `json:"birthday"` Birthday JsonTime `json:"birthday"` Gender string `json:"gender"` Mobile string `json:"mobile"` } // 5.因为gin-应用层web框架 要返回给前端,code码和具体信息(UserListResponse),解决grpc转json格式数据 result := make([]interface{}, 0) for _, value := range rsp.Data { user := response.UserResponse{ Id: value.Id, NickName: value.NickName, //Birthday: time.Time(time.Unix(int64(value.BirthDay), 0)).Format("2006-01-02"), Birthday: response.JsonTime(time.Unix(int64(value.BirthDay), 0)), Gender: value.Gender, Mobile: value.Mobile, } result = append(result, user) } c.JSON(http.StatusOK, result)
-
本文来自博客园,作者:CV-coding,转载请注明原文链接:https://www.cnblogs.com/CV-coding/p/15513748.html
浙公网安备 33010602011771号