Gin框架 、Go Micro集成

  1. 初始化Gin引擎

  2. 注册路由

  3. 运行路由

  4. 添加路由handle方法中,

    • 创建服务

    • 注册微服务客户端

    • 调用服务

    • 响应Response


新建http/main.go

image.png

package mainimport (
    "github.com/asim/go-micro/v3"
    "github.com/gin-gonic/gin"
    helloworld "helloworld/proto")func main() {

    // 初始化引擎
    gin.SetMode(gin.DebugMode)
    router := gin.Default()
    // 注册异常捕获组件
    router.Use(gin.Recovery())

    //注册路由
    router.GET("/", handle)

    //运行路由
    router.Run(":8080")}func handle(c *gin.Context) {

    // 创建服务
    service := micro.NewService(
        micro.Name("go.micro.web.helloworld"),
    )
    service.Init()

    // 创建微服务客户端
    client := helloworld.NewHelloworldService("helloworld", service.Client())

    // 调用服务
    rsp, err := client.Call(c, &helloworld.Request{
        Name: "world!",
    })

    if err != nil {
        c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
        return
    }

    c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})}

服务端,为项目根目录下 helloworld/main.go

详情见上节内容

运行服务

image.png



点赞(442)

评论列表共有 0 条评论

立即
投稿
返回
顶部