Gin框架 、Go Micro集成
- 初始化Gin引擎
- 注册路由
- 运行路由
- 添加路由handle方法中,
- 创建服务
- 注册微服务客户端
- 调用服务
- 响应Response
新建http/main.go
package main
import (
"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