DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

Rest vs GRPC

原文链接

When you use swagger, there is a big temptation not to support the documentation, because it is often an additional problem. When you use gRPC, it will not happen, this improved tool makes the developer’s life easier because it is impossible to write the code without a proto file and without sharing to development teams. 代码与文档部分

gRPC is primarily an RPC framework and it refers to UpdateBalance, GetClient methods.

REST is about resources such a GET /users, POST /users and etc.

grpc-gateway,同时支持grpc和rest部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
syntax = "proto3";

import "google/api/annotations.proto";

package helloworld;

service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {
option(google.api.http) = {
get: "/api/hello/{name}",
};
}
}

message HelloRequest {
string name = 1;
}

message HelloReply {
string message = 1;
}
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
TARGET=helloworld

all: clean build

clean:
rm -rf $(TARGET)

build:
go build -o $(TARGET) main.go

proto:
protoc -I/usr/local/include -I. \
-I${GOPATH}/src \
-I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--go_out=plugins=grpc:. \
pb/hello.proto
protoc -I/usr/local/include -I. \
-I${GOPATH}/src \
-I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--grpc-gateway_out=logtostderr=true:. \
pb/hello.proto
protoc -I/usr/local/include -I. \
-I${GOPATH}/src \
-I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--swagger_out=logtostderr=true:. \
pb/hello.proto

Now there is a small problem — our server will listen two TCP sockets. One is to ensure the operation of the gRPC mechanisms, and the second is to ensure REST. In addition, the gateway will be released as an intermediary, converting the JSON HTTP REST representation into gRPC on the proto files. ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func (g *Greeter) startGRPC() error {
lis, err := net.Listen("tcp", "localhost:8080")
if err != nil {
return err
}
grpcServer := grpc.NewServer()
pb.RegisterGreeterServer(grpcServer, g)
grpcServer.Serve(lis)
return nil
}
func (g *Greeter) startREST() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()

mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
err := pb.RegisterGreeterHandlerFromEndpoint(ctx, mux, ":8080", opts)
if err != nil {
return err
}

return http.ListenAndServe(":8090", mux)
}