非项目目录
go get github.com/go-micro/micro
micro
├── main.go
└── proto
├── build.sh
├── greeter.micro.go
├── greeter.pb.go
└── greeter.proto
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
micro list service
go.micro.srv.greeter
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
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
curl -d 'service=go.micro.srv.greeter' \
-d 'method=Greeter.Hello' \
-d 'request={"name": "Bob"}' \
http://localhost:8080/rpc