1. 项目目录结构
2. 定义main函数
package main
import (
"fmt"
"go.uber.org/zap"
"mxshop-api/user-web/initialize"
)
func main() {
//初始化logger
initialize.InitLogger()
//初始化routes
Router := initialize.Routers()
/*
1. S()可以获取一个全局的sugar,可以让我们自己设置一个全局的logger
2. 日志是分级别的,debug, info , warn, error, fetal
3. S函数和L函数很有用, 提供了一个全局的安全访问logger的途径
*/
zap.S().Infof("启动服务")
port := 8881
if err := Router.Run(fmt.Sprintf(":%d", port)); err != nil {
zap.S().Panic("启动失败:", err.Error())
}
}
3. 定义及初始化logger
在initialize/创建logger.go
package initialize
import "go.uber.org/zap"
func InitLogger() {
logger, _ := zap.NewProduction()
zap.ReplaceGlobals(logger)
}
4. 初始化路由
在initialize/创建router.go
package initialize
import (
"github.com/gin-gonic/gin"
"mxshop-api/user-web/router"
)
func Routers() *gin.Engine {
Router := gin.Default()
ApiGroup := Router.Group("v1")
router.InitUserRoute(ApiGroup)
return Router
}
5.定义路由
在router下创建router.go
package router
import (
"github.com/gin-gonic/gin"
"mxshop-api/user-web/api"
)
func InitUserRoute(Router *gin.RouterGroup) {
UserRouter := Router.Group("user")
{
UserRouter.GET("list", api.GetUserList)
}
}
6. 定义路由调用方法函数
在mxshop-api/user-web/api创建user.go
package api
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"mxshop-api/user-web/global/reponse"
"mxshop-api/user-web/proto"
"net/http"
"time"
)
func HandleGrpcErrorToHttp(err error, c *gin.Context) {
// 将GRPC的code转换成HTTP的状态码
if err != nil {
if e, ok := status.FromError(err); ok {
switch e.Code() {
case codes.NotFound:
c.JSON(http.StatusNotFound, gin.H{
"msg": e.Message(),
})
case codes.Internal:
c.JSON(http.StatusInternalServerError, gin.H{
"msg": "内部错误",
})
case codes.InvalidArgument:
c.JSON(http.StatusBadRequest, gin.H{
"msg": "参数错误",
})
case codes.Unavailable:
c.JSON(http.StatusInternalServerError, gin.H{
"msg": "用户服务不可用",
})
default:
c.JSON(http.StatusInternalServerError, gin.H{
"msg": "其他错误",
})
}
return
}
}
}
func GetUserList(ctx *gin.Context) {
//ip := "127.0.0.1"
//port := "50051"
//拨号连接用户RPC服务
userConn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:50051"), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
zap.S().Errorw("[GetUserList]连接失败【用户服务失败】", "msg", err.Error())
}
//生成grpc的client并调用接口
userSrvClient := proto.NewUserClient(userConn)
rsp, err := userSrvClient.GetUserList(context.Background(), &proto.PageInfo{
Pn: 1,
PSize: 10,
})
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 := reponse.UserResponse{
Id: value.Id,
NickName: value.NickName,
BirthDay: reponse.JsonTime(time.Unix(int64(value.BirthDay), 0)),
//BirthDay: time.Unix(int64(value.BirthDay), 0).Format("2022-01-01"),
//BirthDay: time.Unix(int64(value.BirthDay), 0),
Gender: value.Gender,
Mobile: value.Mobile,
}
result = append(result, user)
}
ctx.JSON(http.StatusOK, result)
}