HelloWorld

最后更新于:2022-04-02 02:49:22

[TOC] ## HelloWorld 不使用 micro 的脚手架工具的一个示例
client.go ``` package main import ( "cap/proto/cap/imooc" "context" "fmt" "github.com/asim/go-micro/v3" ) func main() { service:=micro.NewService( micro.Name("cap.imooc.client"), ) service.Init() capImooc:=imooc.NewCapService("cap.imooc.server",service.Client()) resp, err := capImooc.SayHello(context.TODO(), &imooc.SayRequest{Message: "hello world"}) if err != nil { panic(err) } fmt.Printf("%+v\n", resp) } ```

server.go ``` package main import ( "cap/proto/cap/imooc" "context" "fmt" "github.com/asim/go-micro/v3" ) type CapServer struct {} func (s *CapServer) SayHello(ctx context.Context,req *imooc.SayRequest,resp *imooc.SayResponse)error{ resp.Answer=fmt.Sprintf("我们的口号是%s",req.GetMessage()) return nil } func main() { service :=micro.NewService( micro.Name("cap.imooc.server"), ) service.Init() imooc.RegisterCapHandler(service.Server(),&CapServer{}) err := service.Run() if err != nil { panic(err) } } ```

proto/cap/imooc.proto ``` syntax ="proto3"; package go.micro.service.imooc; option go_package="./imooc"; service Cap{ rpc SayHello(SayRequest)returns(SayResponse){} } message SayRequest { string message = 1; } message SayResponse{ string answer=1; } ```

go.mod ``` module cap go 1.16 require ( github.com/asim/go-micro/v3 v3.5.0 github.com/golang/protobuf v1.4.2 google.golang.org/protobuf v1.23.0 ) ```

1. 编译 proto ``` cd proto/cap protoc --go_out=./ --micro_out=./ *.proto ``` 3. 运行 ``` > go run server.go > go run client.go answer:"我们的口号是hello world" ```
';