1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-23 20:02:22 +00:00

Merge pull request #426 from whtiehack/patch-7

Update ch4-06-grpc-ext.md
This commit is contained in:
chai2010 2019-03-08 11:17:13 +08:00 committed by GitHub
commit 9993837e3f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -240,7 +240,7 @@ func main() {
err := RegisterRestServiceHandlerFromEndpoint(
ctx, mux, "localhost:5000",
grpc.WithInsecure(),
[]grpc.DialOption{grpc.WithInsecure()},
)
if err != nil {
log.Fatal(err)
@ -250,6 +250,26 @@ func main() {
}
```
启动grpc服务 ,端口5000
```go
type RestServiceImpl struct{}
func (r *RestServiceImpl) Get(ctx context.Context, message *StringMessage) (*StringMessage, error) {
return &StringMessage{Value: "Get hi:" + message.Value + "#"}, nil
}
func (r *RestServiceImpl) Post(ctx context.Context, message *StringMessage) (*StringMessage, error) {
return &StringMessage{Value: "Post hi:" + message.Value + "@"}, nil
}
func main() {
grpcServer := grpc.NewServer()
RegisterRestServiceServer(grpcServer, new(RestServiceImpl))
lis, _ := net.Listen("tcp", ":5000")
grpcServer.Serve(lis)
}
```
首先通过runtime.NewServeMux()函数创建路由处理器然后通过RegisterRestServiceHandlerFromEndpoint函数将RestService服务相关的REST接口中转到后面的gRPC服务。grpc-gateway提供的runtime.ServeMux类也实现了http.Handler接口因此可以和标准库中的相关函数配合使用。
当gRPC和REST服务全部启动之后就可以用curl请求REST服务了