Skip to content

Latest commit

 

History

History
105 lines (80 loc) · 1.96 KB

4.Micro命令ExposeHTTP服务.md

File metadata and controls

105 lines (80 loc) · 1.96 KB

4.Micro 命令 Expose HTTP 服务

安装 micro

非项目目录
go get github.com/go-micro/micro

代码

micro
├── main.go
└── proto
    ├── build.sh
    ├── greeter.micro.go
    ├── greeter.pb.go
    └── greeter.proto

micro/main.go

package main

import (
	"context"
	"github.com/cheerego/go-micro-in-action/consul/proto"
	"github.com/micro/go-micro"
	"log"
)

type Greeter struct{}


func (s *Greeter) Hello(ctx context.Context, req *greeter.Request, rsp *greeter.Response) error {
	log.Print("Received Say.Hello request")
	rsp.Greeting = "Hello " + req.Name
	return nil
}

func main() {
	service := micro.NewService(
		micro.Name("go.micro.srv.greeter"),
	)

	// optionally setup command line usage
	service.Init()

	// Register Handlers
	greeter.RegisterGreeterHandler(service.Server(), new(Greeter))

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

go run micro/main.go

查看 mdns 里面注册的服务

micro list service
go.micro.srv.greeter

Expose HTTP Server

micro api
2019/06/23 20:19:07 Registering RPC Handler at /rpc
2019/06/23 20:19:07 Registering API Default Handler at /
2019/06/23 20:19:07 HTTP API Listening on [::]:8080
2019/06/23 20:19:07 Transport [http] Listening on [::]:58742
2019/06/23 20:19:07 Broker [http] Connected to [::]:58743
2019/06/23 20:19:07 Registry [mdns] Registering node: go.micro.api-9caa050c-2e89-4eb7-8c5e-ab45362eee8c

Api访问

curl -H 'Content-Type: application/json' -d '{"name": "Asim"}' http://127.0.0.1:8080/greeter/hello

此时访问会报错,因为这种访问写法的默认的namespace是go.micro.api.greeter,而我们注册的是go.micro.srv.greeter 所以需要把代码改成中的服务名改成srv

Rpc访问

 curl -d 'service=go.micro.srv.greeter' \
        -d 'method=Greeter.Hello' \
        -d 'request={"name": "Bob"}' \
        http://localhost:8080/rpc