微服务实战Go Micro v3 系列(三)-启动HTTP服

这篇就是使用 go-micro 的 http 创建一个可以调用接口的微服务HTTP

源码地址

httpServer

这里我们使用 gin 框架结合 go-micro 来进行编写

首先 创建一个 http 目录,并在该目录下创建 main.go,写入下面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
go复制代码package main

import (
httpServer "github.com/asim/go-micro/plugins/server/http/v3"
"github.com/asim/go-micro/v3"
"github.com/asim/go-micro/v3/logger"
"github.com/asim/go-micro/v3/registry"
"github.com/asim/go-micro/v3/server"
"github.com/gin-gonic/gin"
"go-micro-examples/http/handler"
)

const (
ServerName = "go.micro.web.DemoHTTP" // server name
)

func main() {
// Create service
srv := httpServer.NewServer(
server.Name(ServerName),
server.Address(":8080"),
)

gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.Use(gin.Recovery())

// register router
demo := handler.NewDemo()
demo.InitRouter(router)

hd := srv.NewHandler(router)
if err := srv.Handle(hd); err != nil {
logger.Fatal(err)
}

// Create service
service := micro.NewService(
micro.Server(srv),
micro.Registry(registry.NewRegistry()),
)
service.Init()

// Run service
if err := service.Run(); err != nil {
logger.Fatal(err)
}
}

使用 gin 进行初始化路由

在 http 目录创建 handler\handler.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
go复制代码package handler

import (
"context"
"github.com/asim/go-micro/v3"
"github.com/gin-gonic/gin"
helloworld "go-micro-examples/helloworld/proto"
)

//demo
type demo struct{}

func NewDemo() *demo {
return &demo{}
}

func (a *demo) InitRouter(router *gin.Engine) {
router.POST("/demo", a.demo)
}

func (a *demo) demo(c *gin.Context) {
// create a service
service := micro.NewService()
service.Init()

client := helloworld.NewHelloworldService("go.micro.srv.HelloWorld", service.Client())

rsp, err := client.Call(context.Background(), &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})
}

postman测试

在启动两个微服务之后,如下图:

使用 postman 进行测试,调用成功并返回 “hello world!”

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%