├── .gitignore ├── LICENSE ├── README.md ├── backward-compatibility ├── .clang-format ├── Makefile ├── README.md ├── client │ ├── client │ └── main.go ├── proto │ ├── helloworld.pb.go │ ├── helloworld.proto │ └── helloworld_grpc.pb.go └── server │ ├── main.go │ └── server ├── bazel ├── .clang-format ├── .gitignore ├── BUILD.bazel ├── Makefile ├── README.md ├── WORKSPACE ├── client │ ├── BUILD.bazel │ └── main.go ├── go.mod ├── go.sum ├── proto │ ├── BUILD.bazel │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ ├── BUILD.bazel │ └── main.go ├── bidirectional-streaming ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── proto │ ├── uppercase.pb.go │ └── uppercase.proto └── server │ └── main.go ├── client-side-lb ├── Dockerfile-client ├── Dockerfile-server ├── Makefile ├── README.md ├── client │ └── main.go ├── go.mod ├── go.sum ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go ├── client-streaming ├── .clang-format ├── Makefile ├── README.md ├── client │ ├── main.go │ └── supercar.jpg ├── proto │ ├── uploader.pb.go │ └── uploader.proto └── server │ └── main.go ├── duplicate ├── .clang-format ├── Gopkg.lock ├── Gopkg.toml ├── Makefile ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go ├── enum-compatibility ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── go.mod ├── go.sum ├── proto │ ├── helloworld.proto │ ├── new │ │ ├── helloworld.pb.go │ │ └── helloworld_grpc.pb.go │ └── old │ │ ├── helloworld.pb.go │ │ └── helloworld_grpc.pb.go └── server │ └── main.go ├── envoy-front-proxy ├── Dockerfile-frontenvoy ├── README.md ├── docker-compose.yml └── front-envoy.yaml ├── error-details ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go ├── fieldmask ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── docker-compose.yml ├── go.mod ├── go.sum ├── proto │ ├── go │ │ └── user │ │ │ └── user.pb.go │ └── user.proto └── server │ ├── entity.go │ ├── main.go │ └── mongo.go ├── go-package-option ├── .clang-format ├── Makefile ├── after │ ├── person │ │ ├── person.pb.go │ │ └── person.proto │ └── team │ │ ├── team.pb.go │ │ └── team.proto └── before │ ├── person │ ├── person.pb.go │ └── person.proto │ └── team │ ├── team.pb.go │ └── team.proto ├── go.mod ├── go.sum ├── graceful ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go ├── grpc-gateway ├── .clang-format ├── Dockerfile-gateway ├── Dockerfile-grpc ├── Gopkg.lock ├── Gopkg.toml ├── Makefile ├── README.md ├── gateway │ └── main.go ├── proto │ ├── alive.pb.go │ ├── alive.pb.gw.go │ ├── alive.proto │ ├── user.pb.go │ ├── user.pb.gw.go │ └── user.proto └── server │ └── main.go ├── image-proxy ├── .clang-format ├── Makefile ├── README.md ├── client │ ├── main.go │ └── testimage.png ├── proto │ ├── converter.pb.go │ └── converter.proto └── server │ └── main.go ├── keepalive ├── Makefile ├── README.md ├── client │ └── main.go ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go ├── metadata ├── .clang-format ├── Makefile ├── README.md ├── client │ ├── go.mod │ ├── go.sum │ └── main.go ├── interceptor │ ├── client.go │ └── server.go ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ ├── go.mod │ ├── go.sum │ └── main.go ├── multiple-interceptors ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── interceptor │ ├── client.go │ └── server.go ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go ├── openapi ├── buf.gen.yaml ├── buf.lock ├── buf.yaml └── proto │ ├── alive.proto │ └── user.proto ├── protoc ├── .clang-format ├── Makefile ├── basic │ ├── person.pb.go │ └── person.proto ├── path │ ├── device.pb.go │ ├── device.proto │ ├── path.pb.go │ ├── person.pb.go │ └── person.proto └── plugin │ ├── helloworld.pb.go │ └── helloworld.proto ├── protoeasy ├── .clang-format ├── README.md ├── bar │ └── bar.proto └── foo.proto ├── server-reflection ├── .clang-format ├── Makefile ├── README.md ├── go.mod ├── go.sum ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go ├── server-streaming ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── proto │ ├── feed.pb.go │ └── feed.proto └── server │ └── main.go ├── unary ├── .clang-format ├── Makefile ├── README.md ├── client │ └── main.go ├── go.mod ├── go.sum ├── proto │ ├── helloworld.pb.go │ └── helloworld.proto └── server │ └── main.go └── wait-for-ready ├── Makefile ├── client └── main.go ├── example └── main.go ├── go.mod ├── go.sum ├── proto ├── helloworld.pb.go └── helloworld.proto └── server └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | vendor/ 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Junpei Tsuji 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # grpc-sample 2 | gRPC Samples 3 | 4 | ## Sample list 5 | 6 | - [Protoeasy](https://github.com/jun06t/grpc-sample/tree/master/protoeasy) 7 | - [Unary gRPC](https://github.com/jun06t/grpc-sample/tree/master/unary) 8 | - [Server streaming gRPC](https://github.com/jun06t/grpc-sample/tree/master/server-streaming) 9 | - [Client streaming gRPC](https://github.com/jun06t/grpc-sample/tree/master/client-streaming) 10 | - [Bidirectional streaming gRPC](https://github.com/jun06t/grpc-sample/tree/master/bidirectional-streaming) 11 | - [gRPC Gateway](https://github.com/jun06t/grpc-sample/tree/master/grpc-gateway) 12 | - [Envoy Front Proxy](https://github.com/jun06t/grpc-sample/tree/master/envoy-front-proxy) 13 | - [Image Proxy](https://github.com/jun06t/grpc-sample/tree/master/image-proxy) 14 | 15 | -------------------------------------------------------------------------------- /backward-compatibility/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /backward-compatibility/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=./proto \ 7 | --go_opt=module=github.com/jun06t/grpc-sample/backward-compatibility/proto \ 8 | --go-grpc_out=./proto \ 9 | --go-grpc_opt=module=github.com/jun06t/grpc-sample/backward-compatibility/proto \ 10 | ./proto/*.proto 11 | 12 | proto_format: 13 | find ./proto/ -name "*.proto" | xargs clang-format -i 14 | 15 | -------------------------------------------------------------------------------- /backward-compatibility/README.md: -------------------------------------------------------------------------------- 1 | # Backward compatibility sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | go run client/main.go 16 | ``` 17 | 18 | Then it returns 19 | ``` 20 | 2017/11/14 14:31:42 Reply: Hello alice 21 | ``` 22 | -------------------------------------------------------------------------------- /backward-compatibility/client/client: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jun06t/grpc-sample/4d1542833a64298c22e0d985e8b803e8dedd4bca/backward-compatibility/client/client -------------------------------------------------------------------------------- /backward-compatibility/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | pb "github.com/jun06t/grpc-sample/backward-compatibility/proto" 8 | "google.golang.org/grpc" 9 | ) 10 | 11 | const ( 12 | address = "localhost:8080" 13 | ) 14 | 15 | func main() { 16 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer conn.Close() 21 | 22 | c := pb.NewGreeterClient(conn) 23 | 24 | req := &pb.HelloRequest{ 25 | Name: "alice", 26 | Body: &pb.HelloRequest_Price{ 27 | Price: 10000, 28 | }, 29 | } 30 | resp, err := c.SayHello(context.Background(), req) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | log.Println("Reply: ", resp.Message) 35 | } 36 | -------------------------------------------------------------------------------- /backward-compatibility/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option go_package = "github.com/jun06t/grpc-sample/backward-compatibility/proto;helloworld"; 4 | package helloworld; 5 | 6 | service Greeter { 7 | rpc SayHello(HelloRequest) returns (HelloReply) {} 8 | } 9 | 10 | message HelloRequest { 11 | string name = 1; 12 | 13 | string code = 2; 14 | int64 price = 3; 15 | } 16 | 17 | message HelloReply { 18 | string message = 1; 19 | // Nested nested = 2; 20 | Renamed renamed = 2; 21 | } 22 | 23 | message Nested { 24 | int64 amount = 1; 25 | string name = 2; 26 | message Term { 27 | int64 startAt = 1; 28 | int64 endAt = 2; 29 | } 30 | Term term = 3; 31 | } 32 | 33 | message Renamed { 34 | int64 amount = 1; 35 | string name = 2; 36 | message Term { 37 | int64 startAt = 1; 38 | int64 endAt = 2; 39 | } 40 | Term term = 3; 41 | } 42 | -------------------------------------------------------------------------------- /backward-compatibility/proto/helloworld_grpc.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go-grpc. DO NOT EDIT. 2 | 3 | package helloworld 4 | 5 | import ( 6 | context "context" 7 | grpc "google.golang.org/grpc" 8 | codes "google.golang.org/grpc/codes" 9 | status "google.golang.org/grpc/status" 10 | ) 11 | 12 | // This is a compile-time assertion to ensure that this generated file 13 | // is compatible with the grpc package it is being compiled against. 14 | const _ = grpc.SupportPackageIsVersion7 15 | 16 | // GreeterClient is the client API for Greeter service. 17 | // 18 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. 19 | type GreeterClient interface { 20 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 21 | } 22 | 23 | type greeterClient struct { 24 | cc grpc.ClientConnInterface 25 | } 26 | 27 | func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { 28 | return &greeterClient{cc} 29 | } 30 | 31 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 32 | out := new(HelloReply) 33 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 34 | if err != nil { 35 | return nil, err 36 | } 37 | return out, nil 38 | } 39 | 40 | // GreeterServer is the server API for Greeter service. 41 | // All implementations must embed UnimplementedGreeterServer 42 | // for forward compatibility 43 | type GreeterServer interface { 44 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 45 | mustEmbedUnimplementedGreeterServer() 46 | } 47 | 48 | // UnimplementedGreeterServer must be embedded to have forward compatible implementations. 49 | type UnimplementedGreeterServer struct { 50 | } 51 | 52 | func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) { 53 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 54 | } 55 | func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {} 56 | 57 | // UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service. 58 | // Use of this interface is not recommended, as added methods to GreeterServer will 59 | // result in compilation errors. 60 | type UnsafeGreeterServer interface { 61 | mustEmbedUnimplementedGreeterServer() 62 | } 63 | 64 | func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) { 65 | s.RegisterService(&_Greeter_serviceDesc, srv) 66 | } 67 | 68 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 69 | in := new(HelloRequest) 70 | if err := dec(in); err != nil { 71 | return nil, err 72 | } 73 | if interceptor == nil { 74 | return srv.(GreeterServer).SayHello(ctx, in) 75 | } 76 | info := &grpc.UnaryServerInfo{ 77 | Server: srv, 78 | FullMethod: "/helloworld.Greeter/SayHello", 79 | } 80 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 81 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 82 | } 83 | return interceptor(ctx, in, info, handler) 84 | } 85 | 86 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 87 | ServiceName: "helloworld.Greeter", 88 | HandlerType: (*GreeterServer)(nil), 89 | Methods: []grpc.MethodDesc{ 90 | { 91 | MethodName: "SayHello", 92 | Handler: _Greeter_SayHello_Handler, 93 | }, 94 | }, 95 | Streams: []grpc.StreamDesc{}, 96 | Metadata: "helloworld.proto", 97 | } 98 | -------------------------------------------------------------------------------- /backward-compatibility/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net" 8 | 9 | pb "github.com/jun06t/grpc-sample/backward-compatibility/proto" 10 | "google.golang.org/grpc" 11 | ) 12 | 13 | const ( 14 | port = ":8080" 15 | ) 16 | 17 | type server struct { 18 | pb.UnimplementedGreeterServer 19 | } 20 | 21 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 22 | checkBody(in) 23 | return &pb.HelloReply{ 24 | Message: "Hello " + in.Name, 25 | Renamed: &pb.Renamed{ 26 | Amount: 100, 27 | Name: "foobar", 28 | Term: &pb.Renamed_Term{ 29 | StartAt: 1234567890, 30 | EndAt: 9876543210, 31 | }, 32 | }, 33 | }, nil 34 | } 35 | 36 | func checkBody(in *pb.HelloRequest) { 37 | fmt.Println("price:", in.GetPrice()) 38 | } 39 | 40 | /* 41 | func checkBody(in *pb.HelloRequest) { 42 | switch in.GetBody().(type) { 43 | case *pb.HelloRequest_Code: 44 | fmt.Println("code:", in.GetCode()) 45 | case *pb.HelloRequest_Price: 46 | fmt.Println("price:", in.GetPrice()) 47 | default: 48 | fmt.Println("no body") 49 | } 50 | } 51 | */ 52 | 53 | func main() { 54 | lis, err := net.Listen("tcp", port) 55 | if err != nil { 56 | log.Fatal(err) 57 | } 58 | 59 | s := grpc.NewServer() 60 | pb.RegisterGreeterServer(s, &server{}) 61 | err = s.Serve(lis) 62 | if err != nil { 63 | log.Fatal(err) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /backward-compatibility/server/server: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jun06t/grpc-sample/4d1542833a64298c22e0d985e8b803e8dedd4bca/backward-compatibility/server/server -------------------------------------------------------------------------------- /bazel/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /bazel/.gitignore: -------------------------------------------------------------------------------- 1 | bazel-bazel 2 | bazel-bin 3 | bazel-genfiles 4 | bazel-out 5 | bazel-testlogs 6 | -------------------------------------------------------------------------------- /bazel/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@bazel_gazelle//:def.bzl", "gazelle") 2 | 3 | # gazelle:prefix github.com/jun06t/grpc-sample/bazel 4 | gazelle(name = "gazelle") 5 | -------------------------------------------------------------------------------- /bazel/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | --go_opt=module=github.com/jun06t/grpc-sample/bazel/proto \ 8 | ./proto/*.proto 9 | 10 | proto_format: 11 | find ./proto/ -name "*.proto" | xargs clang-format -i 12 | 13 | -------------------------------------------------------------------------------- /bazel/README.md: -------------------------------------------------------------------------------- 1 | # gRPC Bazel sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | bazel run //server 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | bazel run //client 16 | ``` 17 | 18 | Then it returns 19 | ``` 20 | 2021/12/03 18:28:08 Reply: Hello alice 21 | ``` 22 | -------------------------------------------------------------------------------- /bazel/client/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") 2 | 3 | go_library( 4 | name = "client_lib", 5 | srcs = ["main.go"], 6 | importpath = "github.com/jun06t/grpc-sample/bazel/client", 7 | visibility = ["//visibility:private"], 8 | deps = [ 9 | "//proto", 10 | "@org_golang_google_grpc//:go_default_library", 11 | ], 12 | ) 13 | 14 | go_binary( 15 | name = "client", 16 | embed = [":client_lib"], 17 | visibility = ["//visibility:public"], 18 | ) 19 | -------------------------------------------------------------------------------- /bazel/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | pb "github.com/jun06t/grpc-sample/bazel/proto" 8 | "google.golang.org/grpc" 9 | ) 10 | 11 | const ( 12 | address = "localhost:8080" 13 | ) 14 | 15 | func main() { 16 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer conn.Close() 21 | 22 | c := pb.NewGreeterClient(conn) 23 | 24 | req := &pb.HelloRequest{ 25 | Name: "alice", 26 | } 27 | resp, err := c.SayHello(context.Background(), req) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | log.Println("Reply: ", resp.Message) 32 | } 33 | -------------------------------------------------------------------------------- /bazel/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jun06t/grpc-sample/bazel 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/golang/protobuf v1.5.2 7 | google.golang.org/grpc v1.53.0 8 | google.golang.org/protobuf v1.28.1 9 | ) 10 | 11 | require ( 12 | golang.org/x/net v0.33.0 // indirect 13 | golang.org/x/sys v0.28.0 // indirect 14 | golang.org/x/text v0.21.0 // indirect 15 | google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect 16 | ) 17 | -------------------------------------------------------------------------------- /bazel/proto/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@rules_proto//proto:defs.bzl", "proto_library") 2 | load("@io_bazel_rules_go//go:def.bzl", "go_library") 3 | load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") 4 | 5 | proto_library( 6 | name = "helloworld_proto", 7 | srcs = ["helloworld.proto"], 8 | visibility = ["//visibility:public"], 9 | ) 10 | 11 | go_proto_library( 12 | name = "helloworld_go_proto", 13 | compilers = ["@io_bazel_rules_go//proto:go_grpc"], 14 | importpath = "github.com/jun06t/grpc-sample/bazel/proto", 15 | proto = ":helloworld_proto", 16 | visibility = ["//visibility:public"], 17 | ) 18 | 19 | go_library( 20 | name = "proto", 21 | embed = [":helloworld_go_proto"], 22 | importpath = "github.com/jun06t/grpc-sample/bazel/proto", 23 | visibility = ["//visibility:public"], 24 | ) 25 | -------------------------------------------------------------------------------- /bazel/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | option go_package = "github.com/jun06t/grpc-sample/bazel/proto;helloworld"; 6 | 7 | service Greeter { 8 | rpc SayHello(HelloRequest) returns (HelloReply) {} 9 | } 10 | 11 | message HelloRequest { 12 | string name = 1; 13 | } 14 | 15 | message HelloReply { 16 | string message = 1; 17 | } 18 | -------------------------------------------------------------------------------- /bazel/server/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") 2 | 3 | go_library( 4 | name = "server_lib", 5 | srcs = ["main.go"], 6 | importpath = "github.com/jun06t/grpc-sample/bazel/server", 7 | visibility = ["//visibility:private"], 8 | deps = [ 9 | "//proto", 10 | "@org_golang_google_grpc//:go_default_library", 11 | ], 12 | ) 13 | 14 | go_binary( 15 | name = "server", 16 | embed = [":server_lib"], 17 | visibility = ["//visibility:public"], 18 | ) 19 | -------------------------------------------------------------------------------- /bazel/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "net" 7 | 8 | pb "github.com/jun06t/grpc-sample/bazel/proto" 9 | "google.golang.org/grpc" 10 | ) 11 | 12 | const ( 13 | port = ":8080" 14 | ) 15 | 16 | type server struct{} 17 | 18 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 19 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 20 | } 21 | 22 | func main() { 23 | lis, err := net.Listen("tcp", port) 24 | if err != nil { 25 | log.Fatal(err) 26 | } 27 | 28 | s := grpc.NewServer() 29 | pb.RegisterGreeterServer(s, &server{}) 30 | err = s.Serve(lis) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /bidirectional-streaming/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /bidirectional-streaming/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /bidirectional-streaming/README.md: -------------------------------------------------------------------------------- 1 | # Bidirectional Streaming gRPC sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | go run client/main.go 16 | ``` 17 | 18 | Then it returns the following messages. 19 | ``` 20 | 2017/11/14 14:52:10 send message: tokyo 21 | 2017/11/14 14:52:10 send message: 001 22 | 2017/11/14 14:52:10 send message: Japan 23 | 2017/11/14 14:52:10 received message: TOKYO 24 | 2017/11/14 14:52:10 received message: 001 25 | 2017/11/14 14:52:10 received message: JAPAN 26 | ``` 27 | -------------------------------------------------------------------------------- /bidirectional-streaming/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "io" 6 | "log" 7 | 8 | pb "github.com/jun06t/grpc-sample/bidirectional-streaming/proto" 9 | "google.golang.org/grpc" 10 | ) 11 | 12 | const ( 13 | address = "localhost:8080" 14 | ) 15 | 16 | func main() { 17 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | defer conn.Close() 22 | 23 | client := pb.NewUppercaseServiceClient(conn) 24 | 25 | stream, err := client.Transform(context.Background()) 26 | if err != nil { 27 | log.Fatal(err) 28 | } 29 | done := make(chan struct{}) 30 | 31 | go receive(done, stream) 32 | 33 | data := []string{"tokyo", "001", "Japan"} 34 | err = send(data, stream) 35 | if err != nil { 36 | log.Fatal(err) 37 | } 38 | 39 | <-done 40 | } 41 | 42 | func send(data []string, stream pb.UppercaseService_TransformClient) (err error) { 43 | for _, v := range data { 44 | log.Println("send message: ", v) 45 | err = stream.Send(&pb.UppercaseRequest{Message: v}) 46 | if err != nil { 47 | return err 48 | } 49 | } 50 | err = stream.CloseSend() 51 | if err != nil { 52 | return err 53 | } 54 | 55 | return nil 56 | } 57 | 58 | func receive(done chan struct{}, stream pb.UppercaseService_TransformClient) { 59 | for { 60 | resp, err := stream.Recv() 61 | if err == io.EOF { 62 | // read done. 63 | close(done) 64 | return 65 | } 66 | if err != nil { 67 | log.Fatal(err) 68 | } 69 | log.Println("received message: ", resp.Message) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /bidirectional-streaming/proto/uppercase.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package uppercase; 4 | 5 | service UppercaseService { 6 | rpc Transform(stream UppercaseRequest) returns (stream UppercaseResponse) {} 7 | } 8 | 9 | message UppercaseRequest { 10 | string message = 1; 11 | } 12 | 13 | message UppercaseResponse { 14 | string message = 1; 15 | } 16 | -------------------------------------------------------------------------------- /bidirectional-streaming/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net" 7 | "strings" 8 | 9 | pb "github.com/jun06t/grpc-sample/bidirectional-streaming/proto" 10 | "google.golang.org/grpc" 11 | ) 12 | 13 | const ( 14 | port = ":8080" 15 | ) 16 | 17 | type server struct{} 18 | 19 | func (s *server) Transform(stream pb.UppercaseService_TransformServer) error { 20 | for { 21 | in, err := stream.Recv() 22 | if err == io.EOF { 23 | return nil 24 | } 25 | if err != nil { 26 | return err 27 | } 28 | 29 | resp := &pb.UppercaseResponse{ 30 | Message: strings.ToUpper(in.Message), 31 | } 32 | err = stream.Send(resp) 33 | if err != nil { 34 | return err 35 | } 36 | } 37 | } 38 | 39 | func main() { 40 | lis, err := net.Listen("tcp", port) 41 | if err != nil { 42 | log.Fatal(err) 43 | } 44 | 45 | s := grpc.NewServer() 46 | pb.RegisterUppercaseServiceServer(s, new(server)) 47 | err = s.Serve(lis) 48 | if err != nil { 49 | log.Fatal(err) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /client-side-lb/Dockerfile-client: -------------------------------------------------------------------------------- 1 | FROM golang:1.13-alpine 2 | 3 | ARG REPO="github.com/jun06t/grpc-sample/client-side-lb" 4 | 5 | RUN apk add --update --no-cache git 6 | RUN mkdir -p /go/src/${REPO} 7 | COPY . /go/src/${REPO} 8 | 9 | WORKDIR /go/src/${REPO} 10 | 11 | RUN cd client && go build && mv client /usr/local/bin 12 | 13 | CMD ["client"] 14 | -------------------------------------------------------------------------------- /client-side-lb/Dockerfile-server: -------------------------------------------------------------------------------- 1 | FROM golang:1.13-alpine 2 | 3 | ARG REPO="github.com/jun06t/grpc-sample/client-side-lb" 4 | 5 | RUN apk add --update --no-cache git 6 | RUN mkdir -p /go/src/${REPO} 7 | COPY . /go/src/${REPO} 8 | 9 | WORKDIR /go/src/${REPO} 10 | 11 | RUN cd server && go build && mv server /usr/local/bin 12 | 13 | CMD ["server"] 14 | -------------------------------------------------------------------------------- /client-side-lb/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | REGISTRY_DOMAIN := jun06t 4 | 5 | build: 6 | docker build -f Dockerfile-client -t ${REGISTRY_DOMAIN}/client-side-lb:client . 7 | docker build -f Dockerfile-server -t ${REGISTRY_DOMAIN}/client-side-lb:server . 8 | 9 | push: 10 | docker push ${REGISTRY_DOMAIN}/client-side-lb:client 11 | docker push ${REGISTRY_DOMAIN}/client-side-lb:server 12 | 13 | 14 | proto: proto_format 15 | protoc \ 16 | -I=./proto \ 17 | --go_out=plugins=grpc:./proto \ 18 | ./proto/*.proto 19 | 20 | proto_format: 21 | find ./proto/ -name "*.proto" | xargs clang-format -i 22 | 23 | -------------------------------------------------------------------------------- /client-side-lb/README.md: -------------------------------------------------------------------------------- 1 | # Client Side LB sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | go run client/main.go 16 | ``` 17 | 18 | Then it returns 19 | ``` 20 | 2017/11/14 14:31:42 Reply: Hello alice 21 | 2017/11/14 14:31:43 Reply: Hello alice 22 | ``` 23 | -------------------------------------------------------------------------------- /client-side-lb/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "os" 8 | "time" 9 | 10 | pb "github.com/jun06t/grpc-sample/client-side-lb/proto" 11 | "google.golang.org/grpc" 12 | "google.golang.org/grpc/balancer/roundrobin" 13 | "google.golang.org/grpc/naming" 14 | "google.golang.org/grpc/resolver" 15 | ) 16 | 17 | var ( 18 | endpoint = "localhost:8080" 19 | ) 20 | 21 | func init() { 22 | ep := os.Getenv("ENDPOINT") 23 | if ep != "" { 24 | endpoint = ep 25 | } 26 | } 27 | 28 | func main() { 29 | fmt.Println("Endpoint: ", endpoint) 30 | // conn, err := getConn() 31 | conn, err := getConnDeprecated() 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | defer conn.Close() 36 | 37 | c := pb.NewGreeterClient(conn) 38 | 39 | req := &pb.HelloRequest{ 40 | Name: "alice", 41 | } 42 | for { 43 | resp, err := c.SayHello(context.Background(), req) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | log.Printf("Machine: %s, Reply: %s\n", resp.MachineId, resp.Message) 48 | time.Sleep(1 * time.Second) 49 | } 50 | } 51 | 52 | func getConn() (*grpc.ClientConn, error) { 53 | resolver.SetDefaultScheme("dns") 54 | conn, err := grpc.Dial(endpoint, 55 | grpc.WithInsecure(), 56 | grpc.WithBalancerName(roundrobin.Name), 57 | ) 58 | return conn, err 59 | } 60 | 61 | func getConnDeprecated() (*grpc.ClientConn, error) { 62 | resolver, _ := naming.NewDNSResolverWithFreq(5 * time.Second) 63 | balancer := grpc.RoundRobin(resolver) 64 | conn, err := grpc.Dial(endpoint, 65 | grpc.WithInsecure(), 66 | grpc.WithBalancer(balancer), 67 | ) 68 | return conn, err 69 | } 70 | -------------------------------------------------------------------------------- /client-side-lb/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jun06t/grpc-sample/client-side-lb 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/gofrs/uuid v3.2.0+incompatible 7 | github.com/golang/protobuf v1.5.2 8 | google.golang.org/grpc v1.53.0 9 | ) 10 | -------------------------------------------------------------------------------- /client-side-lb/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | service Greeter { 6 | rpc SayHello(HelloRequest) returns (HelloReply) {} 7 | } 8 | 9 | message HelloRequest { string name = 1; } 10 | 11 | message HelloReply { 12 | string message = 1; 13 | string machine_id = 2; 14 | } 15 | -------------------------------------------------------------------------------- /client-side-lb/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net" 8 | 9 | "github.com/gofrs/uuid" 10 | pb "github.com/jun06t/grpc-sample/client-side-lb/proto" 11 | "google.golang.org/grpc" 12 | ) 13 | 14 | const ( 15 | port = ":8080" 16 | ) 17 | 18 | var machine string 19 | 20 | func init() { 21 | u := uuid.Must(uuid.NewV4()) 22 | machine = u.String() 23 | } 24 | 25 | type server struct{} 26 | 27 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 28 | fmt.Println("request body: ", in.Name) 29 | return &pb.HelloReply{ 30 | Message: "Hello " + in.Name, 31 | MachineId: machine, 32 | }, nil 33 | } 34 | 35 | func main() { 36 | lis, err := net.Listen("tcp", port) 37 | if err != nil { 38 | log.Fatal(err) 39 | } 40 | 41 | s := grpc.NewServer() 42 | pb.RegisterGreeterServer(s, &server{}) 43 | err = s.Serve(lis) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /client-streaming/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /client-streaming/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /client-streaming/README.md: -------------------------------------------------------------------------------- 1 | # Client Streaming gRPC sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | cd server 11 | go run main.go 12 | ``` 13 | 14 | ## Run gRRC Client 15 | ``` 16 | cd client 17 | go run main.go 18 | ``` 19 | 20 | Then it returns the following messages every second. 21 | ``` 22 | 2017/11/14 14:37:10 success 23 | ``` 24 | 25 | And the server's directory has had uploaded image now. 26 | ``` 27 | $ ls 28 | main.go supercar.jpg 29 | ``` 30 | -------------------------------------------------------------------------------- /client-streaming/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "io" 6 | "log" 7 | "os" 8 | 9 | pb "github.com/jun06t/grpc-sample/client-streaming/proto" 10 | "google.golang.org/grpc" 11 | ) 12 | 13 | const ( 14 | address = "localhost:8080" 15 | ) 16 | 17 | func main() { 18 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | defer conn.Close() 23 | 24 | client := pb.NewUploaderClient(conn) 25 | stream, err := client.Upload(context.Background()) 26 | if err != nil { 27 | log.Fatal(err) 28 | } 29 | 30 | err = upload(stream) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | } 35 | 36 | func upload(stream pb.Uploader_UploadClient) error { 37 | file, err := os.Open("supercar.jpg") 38 | if err != nil { 39 | return err 40 | } 41 | defer file.Close() 42 | 43 | buf := make([]byte, 1024) 44 | for { 45 | _, err := file.Read(buf) 46 | if err == io.EOF { 47 | break 48 | } 49 | if err != nil { 50 | return err 51 | } 52 | 53 | stream.Send(&pb.Chunk{Data: buf}) 54 | } 55 | 56 | resp, err := stream.CloseAndRecv() 57 | if err != nil { 58 | return err 59 | } 60 | 61 | log.Println(resp.Status) 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /client-streaming/client/supercar.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jun06t/grpc-sample/4d1542833a64298c22e0d985e8b803e8dedd4bca/client-streaming/client/supercar.jpg -------------------------------------------------------------------------------- /client-streaming/proto/uploader.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package upload; 4 | 5 | service Uploader { 6 | rpc Upload(stream Chunk) returns (UploadResponse) {} 7 | } 8 | 9 | message Chunk { 10 | bytes data = 1; 11 | } 12 | 13 | message UploadResponse { 14 | string status = 1; 15 | } 16 | -------------------------------------------------------------------------------- /client-streaming/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | pb "github.com/jun06t/grpc-sample/client-streaming/proto" 10 | "google.golang.org/grpc" 11 | ) 12 | 13 | const ( 14 | port = ":8080" 15 | ) 16 | 17 | type server struct{} 18 | 19 | func (s *server) Upload(stream pb.Uploader_UploadServer) error { 20 | file, err := os.Create("supercar.jpg") 21 | if err != nil { 22 | return err 23 | } 24 | defer file.Close() 25 | 26 | for { 27 | resp, err := stream.Recv() 28 | if err == io.EOF { 29 | break 30 | } 31 | if err != nil { 32 | return err 33 | } 34 | file.Write(resp.Data) 35 | } 36 | 37 | err = stream.SendAndClose(&pb.UploadResponse{Status: "success"}) 38 | if err != nil { 39 | return err 40 | } 41 | 42 | return nil 43 | } 44 | 45 | func main() { 46 | lis, err := net.Listen("tcp", port) 47 | if err != nil { 48 | log.Fatal(err) 49 | } 50 | 51 | s := grpc.NewServer() 52 | pb.RegisterUploaderServer(s, new(server)) 53 | err = s.Serve(lis) 54 | if err != nil { 55 | log.Fatal(err) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /duplicate/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /duplicate/Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | branch = "master" 6 | digest = "1:3b760d3b93f994df8eb1d9ebfad17d3e9e37edcb7f7efaa15b427c0d7a64f4e4" 7 | name = "github.com/golang/protobuf" 8 | packages = [ 9 | "proto", 10 | "ptypes", 11 | "ptypes/any", 12 | "ptypes/duration", 13 | "ptypes/timestamp", 14 | ] 15 | pruneopts = "" 16 | revision = "1e59b77b52bf8e4b449a57e6f79f21226d571845" 17 | 18 | [[projects]] 19 | branch = "master" 20 | digest = "1:130b1bec86c62e121967ee0c69d9c263dc2d3ffe6c7c9a82aca4071c4d068861" 21 | name = "golang.org/x/net" 22 | packages = [ 23 | "context", 24 | "http2", 25 | "http2/hpack", 26 | "idna", 27 | "internal/timeseries", 28 | "lex/httplex", 29 | "trace", 30 | ] 31 | pruneopts = "" 32 | revision = "9dfe39835686865bff950a07b394c12a98ddc811" 33 | 34 | [[projects]] 35 | branch = "master" 36 | digest = "1:39a1a71adca4b837a25dc6b5fcdd9d175e4597c6d3440f107dfeda31230218e4" 37 | name = "golang.org/x/text" 38 | packages = [ 39 | "collate", 40 | "collate/build", 41 | "internal/colltab", 42 | "internal/gen", 43 | "internal/tag", 44 | "internal/triegen", 45 | "internal/ucd", 46 | "language", 47 | "secure/bidirule", 48 | "transform", 49 | "unicode/bidi", 50 | "unicode/cldr", 51 | "unicode/norm", 52 | "unicode/rangetable", 53 | ] 54 | pruneopts = "" 55 | revision = "88f656faf3f37f690df1a32515b479415e1a6769" 56 | 57 | [[projects]] 58 | branch = "master" 59 | digest = "1:b2a56937cae9680d4c1f8cc6d0a80cbbdd61853510509b80af7ffd9d51366a31" 60 | name = "google.golang.org/genproto" 61 | packages = ["googleapis/rpc/status"] 62 | pruneopts = "" 63 | revision = "11c7f9e547da6db876260ce49ea7536985904c9b" 64 | 65 | [[projects]] 66 | digest = "1:20c0c49f4f37f8de110b7311ee1988d47dfb0413fb3f57a680b187453b5d1d05" 67 | name = "google.golang.org/grpc" 68 | packages = [ 69 | ".", 70 | "balancer", 71 | "codes", 72 | "connectivity", 73 | "credentials", 74 | "grpclb/grpc_lb_v1/messages", 75 | "grpclog", 76 | "internal", 77 | "keepalive", 78 | "metadata", 79 | "naming", 80 | "peer", 81 | "resolver", 82 | "stats", 83 | "status", 84 | "tap", 85 | "transport", 86 | ] 87 | pruneopts = "" 88 | revision = "401e0e00e4bb830a10496d64cd95e068c5bf50de" 89 | version = "v1.7.3" 90 | 91 | [solve-meta] 92 | analyzer-name = "dep" 93 | analyzer-version = 1 94 | input-imports = [ 95 | "github.com/golang/protobuf/proto", 96 | "github.com/golang/protobuf/ptypes/any", 97 | "google.golang.org/grpc", 98 | "google.golang.org/grpc/codes", 99 | "google.golang.org/grpc/status", 100 | ] 101 | solver-name = "gps-cdcl" 102 | solver-version = 1 103 | -------------------------------------------------------------------------------- /duplicate/Gopkg.toml: -------------------------------------------------------------------------------- 1 | 2 | # Gopkg.toml example 3 | # 4 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 5 | # for detailed Gopkg.toml documentation. 6 | # 7 | # required = ["github.com/user/thing/cmd/thing"] 8 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 9 | # 10 | # [[constraint]] 11 | # name = "github.com/user/project" 12 | # version = "1.0.0" 13 | # 14 | # [[constraint]] 15 | # name = "github.com/user/project2" 16 | # branch = "dev" 17 | # source = "github.com/myfork/project2" 18 | # 19 | # [[override]] 20 | # name = "github.com/x/y" 21 | # version = "2.4.0" 22 | 23 | 24 | [[constraint]] 25 | branch = "master" 26 | name = "github.com/golang/protobuf" 27 | 28 | [[constraint]] 29 | name = "google.golang.org/grpc" 30 | version = "1.7.3" 31 | -------------------------------------------------------------------------------- /duplicate/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /duplicate/proto/helloworld.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: helloworld.proto 3 | 4 | package helloworld 5 | 6 | import ( 7 | context "context" 8 | fmt "fmt" 9 | proto "github.com/golang/protobuf/proto" 10 | any "github.com/golang/protobuf/ptypes/any" 11 | grpc "google.golang.org/grpc" 12 | codes "google.golang.org/grpc/codes" 13 | status "google.golang.org/grpc/status" 14 | math "math" 15 | ) 16 | 17 | // Reference imports to suppress errors if they are not otherwise used. 18 | var _ = proto.Marshal 19 | var _ = fmt.Errorf 20 | var _ = math.Inf 21 | 22 | // This is a compile-time assertion to ensure that this generated file 23 | // is compatible with the proto package it is being compiled against. 24 | // A compilation error at this line likely means your copy of the 25 | // proto package needs to be updated. 26 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 27 | 28 | type HelloReply struct { 29 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` 30 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 31 | XXX_unrecognized []byte `json:"-"` 32 | XXX_sizecache int32 `json:"-"` 33 | } 34 | 35 | func (m *HelloReply) Reset() { *m = HelloReply{} } 36 | func (m *HelloReply) String() string { return proto.CompactTextString(m) } 37 | func (*HelloReply) ProtoMessage() {} 38 | func (*HelloReply) Descriptor() ([]byte, []int) { 39 | return fileDescriptor_17b8c58d586b62f2, []int{0} 40 | } 41 | 42 | func (m *HelloReply) XXX_Unmarshal(b []byte) error { 43 | return xxx_messageInfo_HelloReply.Unmarshal(m, b) 44 | } 45 | func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 46 | return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) 47 | } 48 | func (m *HelloReply) XXX_Merge(src proto.Message) { 49 | xxx_messageInfo_HelloReply.Merge(m, src) 50 | } 51 | func (m *HelloReply) XXX_Size() int { 52 | return xxx_messageInfo_HelloReply.Size(m) 53 | } 54 | func (m *HelloReply) XXX_DiscardUnknown() { 55 | xxx_messageInfo_HelloReply.DiscardUnknown(m) 56 | } 57 | 58 | var xxx_messageInfo_HelloReply proto.InternalMessageInfo 59 | 60 | func (m *HelloReply) GetMessage() string { 61 | if m != nil { 62 | return m.Message 63 | } 64 | return "" 65 | } 66 | 67 | func init() { 68 | proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") 69 | } 70 | 71 | func init() { proto.RegisterFile("helloworld.proto", fileDescriptor_17b8c58d586b62f2) } 72 | 73 | var fileDescriptor_17b8c58d586b62f2 = []byte{ 74 | // 144 bytes of a gzipped FileDescriptorProto 75 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0x48, 0xcd, 0xc9, 76 | 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, 77 | 0x48, 0x49, 0xa6, 0xe7, 0xe7, 0xa7, 0xe7, 0xa4, 0xea, 0x83, 0x65, 0x92, 0x4a, 0xd3, 0xf4, 0x13, 78 | 0xf3, 0x2a, 0x21, 0xca, 0x94, 0xd4, 0xb8, 0xb8, 0x3c, 0x40, 0x0a, 0x83, 0x52, 0x0b, 0x72, 0x2a, 79 | 0x85, 0x24, 0xb8, 0xd8, 0x73, 0x53, 0x8b, 0x8b, 0x13, 0xd3, 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 80 | 0x38, 0x83, 0x60, 0x5c, 0x23, 0x57, 0x2e, 0x76, 0xf7, 0xa2, 0xd4, 0xd4, 0x92, 0xd4, 0x22, 0x21, 81 | 0x2b, 0x2e, 0x8e, 0xe0, 0xc4, 0x4a, 0xb0, 0x2e, 0x21, 0x11, 0x3d, 0x88, 0xd1, 0x7a, 0x30, 0xa3, 82 | 0xf5, 0x1c, 0xf3, 0x2a, 0xa5, 0xc4, 0xf4, 0x90, 0x9c, 0x83, 0x30, 0x5e, 0x89, 0x21, 0x89, 0x0d, 83 | 0xac, 0xce, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xfc, 0xb3, 0x1b, 0x3e, 0xb0, 0x00, 0x00, 0x00, 84 | } 85 | 86 | // Reference imports to suppress errors if they are not otherwise used. 87 | var _ context.Context 88 | var _ grpc.ClientConn 89 | 90 | // This is a compile-time assertion to ensure that this generated file 91 | // is compatible with the grpc package it is being compiled against. 92 | const _ = grpc.SupportPackageIsVersion4 93 | 94 | // GreeterClient is the client API for Greeter service. 95 | // 96 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. 97 | type GreeterClient interface { 98 | SayHello(ctx context.Context, in *any.Any, opts ...grpc.CallOption) (*HelloReply, error) 99 | } 100 | 101 | type greeterClient struct { 102 | cc *grpc.ClientConn 103 | } 104 | 105 | func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { 106 | return &greeterClient{cc} 107 | } 108 | 109 | func (c *greeterClient) SayHello(ctx context.Context, in *any.Any, opts ...grpc.CallOption) (*HelloReply, error) { 110 | out := new(HelloReply) 111 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 112 | if err != nil { 113 | return nil, err 114 | } 115 | return out, nil 116 | } 117 | 118 | // GreeterServer is the server API for Greeter service. 119 | type GreeterServer interface { 120 | SayHello(context.Context, *any.Any) (*HelloReply, error) 121 | } 122 | 123 | // UnimplementedGreeterServer can be embedded to have forward compatible implementations. 124 | type UnimplementedGreeterServer struct { 125 | } 126 | 127 | func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *any.Any) (*HelloReply, error) { 128 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 129 | } 130 | 131 | func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { 132 | s.RegisterService(&_Greeter_serviceDesc, srv) 133 | } 134 | 135 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 136 | in := new(any.Any) 137 | if err := dec(in); err != nil { 138 | return nil, err 139 | } 140 | if interceptor == nil { 141 | return srv.(GreeterServer).SayHello(ctx, in) 142 | } 143 | info := &grpc.UnaryServerInfo{ 144 | Server: srv, 145 | FullMethod: "/helloworld.Greeter/SayHello", 146 | } 147 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 148 | return srv.(GreeterServer).SayHello(ctx, req.(*any.Any)) 149 | } 150 | return interceptor(ctx, in, info, handler) 151 | } 152 | 153 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 154 | ServiceName: "helloworld.Greeter", 155 | HandlerType: (*GreeterServer)(nil), 156 | Methods: []grpc.MethodDesc{ 157 | { 158 | MethodName: "SayHello", 159 | Handler: _Greeter_SayHello_Handler, 160 | }, 161 | }, 162 | Streams: []grpc.StreamDesc{}, 163 | Metadata: "helloworld.proto", 164 | } 165 | -------------------------------------------------------------------------------- /duplicate/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | import "google/protobuf/any.proto"; 4 | 5 | package helloworld; 6 | 7 | service Greeter { 8 | rpc SayHello(google.protobuf.Any) returns (HelloReply) {} 9 | } 10 | 11 | message HelloReply { 12 | string message = 1; 13 | } 14 | -------------------------------------------------------------------------------- /duplicate/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "net" 7 | 8 | "github.com/golang/protobuf/ptypes/any" 9 | pb "github.com/jun06t/grpc-sample/duplicate/proto" 10 | "google.golang.org/grpc" 11 | ) 12 | 13 | const ( 14 | port = ":8080" 15 | ) 16 | 17 | type server struct{} 18 | 19 | func (s *server) SayHello(ctx context.Context, in *any.Any) (*pb.HelloReply, error) { 20 | return &pb.HelloReply{Message: "Hello "}, nil 21 | } 22 | 23 | func main() { 24 | lis, err := net.Listen("tcp", port) 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | 29 | s := grpc.NewServer() 30 | pb.RegisterGreeterServer(s, &server{}) 31 | err = s.Serve(lis) 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /enum-compatibility/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /enum-compatibility/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=./proto \ 7 | --go_opt=module=github.com/jun06t/grpc-sample/enum-compatibility/proto \ 8 | --go-grpc_out=./proto \ 9 | --go-grpc_opt=module=github.com/jun06t/grpc-sample/enum-compatibility/proto \ 10 | ./proto/*.proto 11 | 12 | proto_format: 13 | find ./proto/ -name "*.proto" | xargs clang-format -i 14 | 15 | -------------------------------------------------------------------------------- /enum-compatibility/README.md: -------------------------------------------------------------------------------- 1 | # Enum compatibility check 2 | ## Premise 3 | Old proto is following. 4 | 5 | ```proto 6 | message HelloReply { 7 | string message = 1; 8 | enum Role { 9 | NONE = 0; 10 | STANDARD = 1; 11 | PREMIUM = 2; 12 | ULTIMATE = 3; 13 | } 14 | Role role = 2; 15 | } 16 | ``` 17 | 18 | Then I update like this. 19 | ```proto 20 | message HelloReply { 21 | string message = 1; 22 | RoleType role = 2; 23 | } 24 | 25 | enum RoleType { 26 | NONE = 0; 27 | STANDARD = 1; 28 | PREMIUM = 2; 29 | ULTIMATE = 3; 30 | } 31 | ``` 32 | 33 | ## Confirm behaviour 34 | ### Run gRPC server 35 | Server depends on new enum proto ``RoleType``. 36 | ``` 37 | go run server/main.go 38 | ``` 39 | 40 | ### Run gRRC Client 41 | Client depends on old enum proto ``HelloReply.Role``. 42 | ``` 43 | go run client/main.go 44 | ``` 45 | 46 | ### Result 47 | Then it returns 48 | ``` 49 | 2024/11/13 08:50:49 Reply: Hello alice 50 | 2024/11/13 08:50:49 Role: ULTIMATE 51 | ``` 52 | This means Enum's rename doesn't break compatibility. -------------------------------------------------------------------------------- /enum-compatibility/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | pb "github.com/jun06t/grpc-sample/enum-compatibility/proto/old" 8 | "google.golang.org/grpc" 9 | ) 10 | 11 | const ( 12 | address = "localhost:8080" 13 | ) 14 | 15 | func main() { 16 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer conn.Close() 21 | 22 | c := pb.NewGreeterClient(conn) 23 | 24 | req := &pb.HelloRequest{ 25 | Name: "alice", 26 | } 27 | resp, err := c.SayHello(context.Background(), req) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | log.Println("Reply: ", resp.Message) 32 | log.Println("Role: ", resp.Role.String()) 33 | } 34 | -------------------------------------------------------------------------------- /enum-compatibility/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jun06t/grpc-sample/enum-compatibility 2 | 3 | go 1.23.3 4 | 5 | require ( 6 | google.golang.org/grpc v1.68.0 7 | google.golang.org/protobuf v1.35.1 8 | ) 9 | 10 | require ( 11 | golang.org/x/net v0.29.0 // indirect 12 | golang.org/x/sys v0.25.0 // indirect 13 | golang.org/x/text v0.18.0 // indirect 14 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 // indirect 15 | ) 16 | -------------------------------------------------------------------------------- /enum-compatibility/go.sum: -------------------------------------------------------------------------------- 1 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= 2 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= 3 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 4 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 5 | golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= 6 | golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= 7 | golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= 8 | golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 9 | golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= 10 | golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 11 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 h1:pPJltXNxVzT4pK9yD8vR9X75DaWYYmLGMsEvBfFQZzQ= 12 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= 13 | google.golang.org/grpc v1.68.0 h1:aHQeeJbo8zAkAa3pRzrVjZlbz6uSfeOXlJNQM0RAbz0= 14 | google.golang.org/grpc v1.68.0/go.mod h1:fmSPC5AsjSBCK54MyHRx48kpOti1/jRfOlwEWywNjWA= 15 | google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= 16 | google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= 17 | -------------------------------------------------------------------------------- /enum-compatibility/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option go_package = "github.com/jun06t/grpc-sample/enum-compatibility/proto"; 4 | 5 | package helloworld; 6 | 7 | service Greeter { 8 | rpc SayHello(HelloRequest) returns (HelloReply) {} 9 | } 10 | 11 | message HelloRequest { 12 | string name = 1; 13 | } 14 | 15 | message HelloReply { 16 | string message = 1; 17 | /* 18 | enum Role { 19 | NONE = 0; 20 | STANDARD = 1; 21 | PREMIUM = 2; 22 | ULTIMATE = 3; 23 | } 24 | Role role = 2; 25 | */ 26 | RoleType role = 2; 27 | } 28 | 29 | enum RoleType { 30 | NONE = 0; 31 | STANDARD = 1; 32 | PREMIUM = 2; 33 | ULTIMATE = 3; 34 | } 35 | -------------------------------------------------------------------------------- /enum-compatibility/proto/new/helloworld_grpc.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go-grpc. DO NOT EDIT. 2 | 3 | package proto 4 | 5 | import ( 6 | context "context" 7 | grpc "google.golang.org/grpc" 8 | codes "google.golang.org/grpc/codes" 9 | status "google.golang.org/grpc/status" 10 | ) 11 | 12 | // This is a compile-time assertion to ensure that this generated file 13 | // is compatible with the grpc package it is being compiled against. 14 | const _ = grpc.SupportPackageIsVersion7 15 | 16 | // GreeterClient is the client API for Greeter service. 17 | // 18 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. 19 | type GreeterClient interface { 20 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 21 | } 22 | 23 | type greeterClient struct { 24 | cc grpc.ClientConnInterface 25 | } 26 | 27 | func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { 28 | return &greeterClient{cc} 29 | } 30 | 31 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 32 | out := new(HelloReply) 33 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 34 | if err != nil { 35 | return nil, err 36 | } 37 | return out, nil 38 | } 39 | 40 | // GreeterServer is the server API for Greeter service. 41 | // All implementations must embed UnimplementedGreeterServer 42 | // for forward compatibility 43 | type GreeterServer interface { 44 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 45 | mustEmbedUnimplementedGreeterServer() 46 | } 47 | 48 | // UnimplementedGreeterServer must be embedded to have forward compatible implementations. 49 | type UnimplementedGreeterServer struct { 50 | } 51 | 52 | func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) { 53 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 54 | } 55 | func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {} 56 | 57 | // UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service. 58 | // Use of this interface is not recommended, as added methods to GreeterServer will 59 | // result in compilation errors. 60 | type UnsafeGreeterServer interface { 61 | mustEmbedUnimplementedGreeterServer() 62 | } 63 | 64 | func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) { 65 | s.RegisterService(&_Greeter_serviceDesc, srv) 66 | } 67 | 68 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 69 | in := new(HelloRequest) 70 | if err := dec(in); err != nil { 71 | return nil, err 72 | } 73 | if interceptor == nil { 74 | return srv.(GreeterServer).SayHello(ctx, in) 75 | } 76 | info := &grpc.UnaryServerInfo{ 77 | Server: srv, 78 | FullMethod: "/helloworld.Greeter/SayHello", 79 | } 80 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 81 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 82 | } 83 | return interceptor(ctx, in, info, handler) 84 | } 85 | 86 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 87 | ServiceName: "helloworld.Greeter", 88 | HandlerType: (*GreeterServer)(nil), 89 | Methods: []grpc.MethodDesc{ 90 | { 91 | MethodName: "SayHello", 92 | Handler: _Greeter_SayHello_Handler, 93 | }, 94 | }, 95 | Streams: []grpc.StreamDesc{}, 96 | Metadata: "helloworld.proto", 97 | } 98 | -------------------------------------------------------------------------------- /enum-compatibility/proto/old/helloworld_grpc.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go-grpc. DO NOT EDIT. 2 | 3 | package proto 4 | 5 | import ( 6 | context "context" 7 | grpc "google.golang.org/grpc" 8 | codes "google.golang.org/grpc/codes" 9 | status "google.golang.org/grpc/status" 10 | ) 11 | 12 | // This is a compile-time assertion to ensure that this generated file 13 | // is compatible with the grpc package it is being compiled against. 14 | const _ = grpc.SupportPackageIsVersion7 15 | 16 | // GreeterClient is the client API for Greeter service. 17 | // 18 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. 19 | type GreeterClient interface { 20 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 21 | } 22 | 23 | type greeterClient struct { 24 | cc grpc.ClientConnInterface 25 | } 26 | 27 | func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { 28 | return &greeterClient{cc} 29 | } 30 | 31 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 32 | out := new(HelloReply) 33 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 34 | if err != nil { 35 | return nil, err 36 | } 37 | return out, nil 38 | } 39 | 40 | // GreeterServer is the server API for Greeter service. 41 | // All implementations must embed UnimplementedGreeterServer 42 | // for forward compatibility 43 | type GreeterServer interface { 44 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 45 | mustEmbedUnimplementedGreeterServer() 46 | } 47 | 48 | // UnimplementedGreeterServer must be embedded to have forward compatible implementations. 49 | type UnimplementedGreeterServer struct { 50 | } 51 | 52 | func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) { 53 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 54 | } 55 | func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {} 56 | 57 | // UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service. 58 | // Use of this interface is not recommended, as added methods to GreeterServer will 59 | // result in compilation errors. 60 | type UnsafeGreeterServer interface { 61 | mustEmbedUnimplementedGreeterServer() 62 | } 63 | 64 | func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) { 65 | s.RegisterService(&_Greeter_serviceDesc, srv) 66 | } 67 | 68 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 69 | in := new(HelloRequest) 70 | if err := dec(in); err != nil { 71 | return nil, err 72 | } 73 | if interceptor == nil { 74 | return srv.(GreeterServer).SayHello(ctx, in) 75 | } 76 | info := &grpc.UnaryServerInfo{ 77 | Server: srv, 78 | FullMethod: "/helloworld.Greeter/SayHello", 79 | } 80 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 81 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 82 | } 83 | return interceptor(ctx, in, info, handler) 84 | } 85 | 86 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 87 | ServiceName: "helloworld.Greeter", 88 | HandlerType: (*GreeterServer)(nil), 89 | Methods: []grpc.MethodDesc{ 90 | { 91 | MethodName: "SayHello", 92 | Handler: _Greeter_SayHello_Handler, 93 | }, 94 | }, 95 | Streams: []grpc.StreamDesc{}, 96 | Metadata: "helloworld.proto", 97 | } 98 | -------------------------------------------------------------------------------- /enum-compatibility/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "net" 7 | 8 | pb "github.com/jun06t/grpc-sample/enum-compatibility/proto/new" 9 | "google.golang.org/grpc" 10 | ) 11 | 12 | const ( 13 | port = ":8080" 14 | ) 15 | 16 | type server struct { 17 | pb.UnimplementedGreeterServer 18 | } 19 | 20 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 21 | return &pb.HelloReply{ 22 | Message: "Hello " + in.Name, 23 | Role: pb.RoleType_ULTIMATE, 24 | }, nil 25 | } 26 | 27 | func main() { 28 | lis, err := net.Listen("tcp", port) 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | 33 | s := grpc.NewServer() 34 | pb.RegisterGreeterServer(s, &server{}) 35 | err = s.Serve(lis) 36 | if err != nil { 37 | log.Fatal(err) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /envoy-front-proxy/Dockerfile-frontenvoy: -------------------------------------------------------------------------------- 1 | FROM envoyproxy/envoy:latest 2 | 3 | RUN apt-get update && apt-get -q install -y \ 4 | curl 5 | CMD /usr/local/bin/envoy -c /etc/front-envoy.yaml --service-cluster front-proxy 6 | -------------------------------------------------------------------------------- /envoy-front-proxy/README.md: -------------------------------------------------------------------------------- 1 | # Envoy front proxy sample 2 | 3 | ## Run servers 4 | ``` 5 | docker-compose up -d 6 | ``` 7 | 8 | ## Scale out backend servers 9 | ``` 10 | docker-compose up --scale grpc=3 11 | ``` 12 | 13 | ## Confirm Admin statistics 14 | http://localhost:8001 15 | 16 | ## Send Request 17 | ### Alive 18 | ``` 19 | curl http://localhost:3000/alive 20 | ``` 21 | 22 | ### Get User 23 | ``` 24 | curl http://localhost:3000/user/100 25 | ``` 26 | 27 | ### Get Users By Group 28 | ``` 29 | curl http://localhost:3000/user?group=ADMIN 30 | ``` 31 | 32 | ### Update User 33 | ``` 34 | curl -XPUT http://localhost:3000/user/100 -d '{"name": "bob", "age": 16}' 35 | ``` 36 | -------------------------------------------------------------------------------- /envoy-front-proxy/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2.4' 2 | services: 3 | 4 | gateway: 5 | image: jun06t/grpc-gateway 6 | networks: 7 | - front-proxy 8 | expose: 9 | - "3000" 10 | ports: 11 | - "3000:3000" 12 | environment: 13 | - ENDPOINT=front-proxy:8000 14 | 15 | front-envoy: 16 | build: 17 | context: . 18 | dockerfile: Dockerfile-frontenvoy 19 | container_name: front-proxy 20 | volumes: 21 | - ./front-envoy.yaml:/etc/front-envoy.yaml 22 | networks: 23 | - front-proxy 24 | expose: 25 | - "8000" 26 | - "8001" 27 | ports: 28 | - "8001:8001" 29 | 30 | grpc: 31 | image: jun06t/grpc-backend 32 | networks: 33 | front-proxy: 34 | aliases: 35 | - backend 36 | expose: 37 | - "8080" 38 | 39 | networks: 40 | front-proxy: {} 41 | -------------------------------------------------------------------------------- /envoy-front-proxy/front-envoy.yaml: -------------------------------------------------------------------------------- 1 | static_resources: 2 | listeners: 3 | - address: 4 | socket_address: 5 | address: 0.0.0.0 6 | port_value: 8000 7 | filter_chains: 8 | - filters: 9 | - name: envoy.http_connection_manager 10 | config: 11 | codec_type: auto 12 | stat_prefix: ingress_http 13 | route_config: 14 | name: local_route 15 | virtual_hosts: 16 | - name: backend 17 | domains: 18 | - "*" 19 | routes: 20 | - match: 21 | prefix: "/" 22 | route: 23 | cluster: grpc 24 | access_log: 25 | - name: envoy.file_access_log 26 | config: 27 | path: "/dev/stdout" 28 | http_filters: 29 | - name: envoy.router 30 | config: {} 31 | clusters: 32 | - name: grpc 33 | connect_timeout: 0.25s 34 | type: strict_dns 35 | lb_policy: round_robin 36 | http2_protocol_options: {} 37 | health_checks: 38 | - timeout: 5s 39 | interval: 10s 40 | unhealthy_threshold: 2 41 | healthy_threshold: 2 42 | tcp_health_check: {} 43 | hosts: 44 | - socket_address: 45 | address: backend 46 | port_value: 8080 47 | admin: 48 | access_log_path: /dev/null 49 | address: 50 | socket_address: 51 | address: 0.0.0.0 52 | port_value: 8001 53 | -------------------------------------------------------------------------------- /error-details/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /error-details/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /error-details/README.md: -------------------------------------------------------------------------------- 1 | # Error Details example 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | Server returns random response. 15 | 16 | ``` 17 | error-details $ go run client/main.go 18 | error code: EXPIRED_RECEIPT 19 | 2019/09/05 08:00:07 rpc error: code = InvalidArgument desc = some error occurred 20 | exit status 1 21 | error-details $ go run client/main.go 22 | 2019/09/05 08:00:08 Reply: Hello alice 23 | error-details $ go run client/main.go 24 | handle BadRequest case 25 | 2019/09/05 08:00:10 rpc error: code = InvalidArgument desc = some error occurred 26 | exit status 1 27 | error-details $ go run client/main.go 28 | error code: INVALID_COUNTRY 29 | 2019/09/05 08:00:12 rpc error: code = InvalidArgument desc = some error occurred 30 | exit status 1 31 | error-details $ go run client/main.go 32 | handle QuotaFailure case 33 | 2019/09/05 08:00:13 rpc error: code = InvalidArgument desc = some error occurred 34 | exit status 1 35 | ``` 36 | -------------------------------------------------------------------------------- /error-details/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | pb "github.com/jun06t/grpc-sample/error-details/proto" 9 | "google.golang.org/genproto/googleapis/rpc/errdetails" 10 | "google.golang.org/grpc" 11 | "google.golang.org/grpc/status" 12 | ) 13 | 14 | const ( 15 | address = "localhost:8080" 16 | ) 17 | 18 | func main() { 19 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | defer conn.Close() 24 | 25 | c := pb.NewGreeterClient(conn) 26 | 27 | req := &pb.HelloRequest{ 28 | Name: "alice", 29 | } 30 | resp, err := c.SayHello(context.Background(), req) 31 | if err != nil { 32 | handleError(err) 33 | log.Fatal(err) 34 | } 35 | log.Println("Reply: ", resp.Message) 36 | } 37 | 38 | func handleError(err error) { 39 | st, _ := status.FromError(err) 40 | 41 | for _, detail := range st.Details() { 42 | switch t := detail.(type) { 43 | case *errdetails.BadRequest: 44 | fmt.Println("handle BadRequest case") 45 | case *errdetails.QuotaFailure: 46 | fmt.Println("handle QuotaFailure case") 47 | case *pb.ErrorDetail: 48 | // handle original error code 49 | fmt.Println("error code:", t.Code) 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /error-details/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | service Greeter { 6 | rpc SayHello(HelloRequest) returns (HelloReply) {} 7 | } 8 | 9 | message HelloRequest { 10 | string name = 1; 11 | } 12 | 13 | message HelloReply { 14 | string message = 1; 15 | } 16 | 17 | enum ErrorCode { 18 | UNKNOWN = 0; 19 | INVALID_RECEIPT = 1; 20 | EXPIRED_RECEIPT = 2; 21 | INVALID_CARD = 3; 22 | EXPIRED_CARD = 4; 23 | INVALID_COUNTRY = 5; 24 | PREPAID_CARD = 6; 25 | } 26 | 27 | message ErrorDetail { 28 | ErrorCode code = 1; 29 | string message = 2; 30 | } 31 | -------------------------------------------------------------------------------- /error-details/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "math/rand" 7 | "net" 8 | 9 | pb "github.com/jun06t/grpc-sample/error-details/proto" 10 | "google.golang.org/genproto/googleapis/rpc/errdetails" 11 | "google.golang.org/grpc" 12 | "google.golang.org/grpc/codes" 13 | "google.golang.org/grpc/status" 14 | ) 15 | 16 | const ( 17 | port = ":8080" 18 | ) 19 | 20 | type server struct{} 21 | 22 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 23 | n := rand.Intn(5) // エラーレスポンスを返すためのランダム値 24 | switch n { 25 | case 0: 26 | st := status.New(codes.InvalidArgument, "some error occurred") 27 | v := &errdetails.QuotaFailure{ 28 | Violations: []*errdetails.QuotaFailure_Violation{ 29 | { 30 | Subject: "clientip:", 31 | Description: "Daily Limit was exceeded for SayHello", 32 | }, 33 | }, 34 | } 35 | dt, _ := st.WithDetails(v) 36 | return nil, dt.Err() 37 | case 1: 38 | st := status.New(codes.InvalidArgument, "some error occurred") 39 | v := &errdetails.BadRequest{ 40 | FieldViolations: []*errdetails.BadRequest_FieldViolation{ 41 | { 42 | Field: "username", 43 | Description: "should not empty", 44 | }, 45 | }, 46 | } 47 | dt, _ := st.WithDetails(v) 48 | return nil, dt.Err() 49 | case 2: 50 | st := status.New(codes.InvalidArgument, "some error occurred") 51 | dt, _ := st.WithDetails(&pb.ErrorDetail{Code: pb.ErrorCode_EXPIRED_RECEIPT}) 52 | return nil, dt.Err() 53 | case 3: 54 | st := status.New(codes.InvalidArgument, "some error occurred") 55 | dt, _ := st.WithDetails(&pb.ErrorDetail{Code: pb.ErrorCode_INVALID_COUNTRY}) 56 | return nil, dt.Err() 57 | } 58 | 59 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 60 | } 61 | 62 | func main() { 63 | lis, err := net.Listen("tcp", port) 64 | if err != nil { 65 | log.Fatal(err) 66 | } 67 | 68 | s := grpc.NewServer() 69 | pb.RegisterGreeterServer(s, &server{}) 70 | err = s.Serve(lis) 71 | if err != nil { 72 | log.Fatal(err) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /fieldmask/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /fieldmask/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto/go \ 7 | --go_opt=module=github.com/jun06t/grpc-sample/fieldmask/proto/go \ 8 | ./proto/*.proto 9 | 10 | proto_format: 11 | find ./proto/ -name "*.proto" | xargs clang-format -i 12 | 13 | -------------------------------------------------------------------------------- /fieldmask/README.md: -------------------------------------------------------------------------------- 1 | # Fieldmask sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | go run client/main.go 16 | ``` 17 | 18 | Then it returns 19 | ``` 20 | 2022/07/08 19:18:09 user:{id:"001" name:"alice" email:"alice@gmail.com" age:20 address:{country:"Japan" state:"Tokyo" city:"Shibuya" zipcode:"150-0000"}} 21 | 2022/07/08 19:18:09 user:{name:"alice" age:20 address:{city:"Shibuya"}} 22 | 2022/07/08 19:18:09 user:{id:"001" name:"bob" age:20 address:{city:"Ikebukuro" zipcode:"170-0000"}} 23 | ``` 24 | -------------------------------------------------------------------------------- /fieldmask/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "log" 8 | 9 | pb "github.com/jun06t/grpc-sample/fieldmask/proto/go/user" 10 | "google.golang.org/grpc" 11 | "google.golang.org/protobuf/types/known/fieldmaskpb" 12 | ) 13 | 14 | const ( 15 | address = "localhost:8080" 16 | ) 17 | 18 | func main() { 19 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | 24 | c := newClient(conn) 25 | defer c.Close() 26 | 27 | c.Save() 28 | c.Get() 29 | c.GetWithMask() 30 | c.SaveWithMask() 31 | c.Get() 32 | } 33 | 34 | type Client struct { 35 | conn *grpc.ClientConn 36 | cli pb.UserServiceClient 37 | } 38 | 39 | func newClient(conn *grpc.ClientConn) *Client { 40 | cli := pb.NewUserServiceClient(conn) 41 | return &Client{ 42 | conn: conn, 43 | cli: cli, 44 | } 45 | } 46 | 47 | func (c *Client) Get() error { 48 | req := &pb.GetRequest{ 49 | Id: "001", 50 | } 51 | resp, err := c.cli.Get(context.Background(), req) 52 | if err != nil { 53 | return err 54 | } 55 | 56 | b, _ := json.Marshal(resp) 57 | fmt.Println(string(b)) 58 | return nil 59 | } 60 | 61 | func (c *Client) Save() error { 62 | req := &pb.UpdateRequest{ 63 | User: &pb.User{ 64 | Id: "001", 65 | Name: "alice", 66 | Age: 20, 67 | Email: "alice@gmail.com", 68 | Address: &pb.Address{ 69 | Country: "Japan", 70 | State: "Tokyo", 71 | City: "Shibuya", 72 | Zipcode: "150-0000", 73 | }, 74 | }, 75 | } 76 | _, err := c.cli.Update(context.Background(), req) 77 | if err != nil { 78 | return err 79 | } 80 | return nil 81 | } 82 | 83 | func (c *Client) GetWithMask() error { 84 | paths := []string{"name", "age", "address.city"} 85 | fm := fieldmaskpb.FieldMask{Paths: paths} 86 | req := &pb.GetRequest{ 87 | Id: "001", 88 | FieldMask: &fm, 89 | } 90 | resp, err := c.cli.Get(context.Background(), req) 91 | if err != nil { 92 | return err 93 | } 94 | b, _ := json.Marshal(resp) 95 | fmt.Println(string(b)) 96 | return nil 97 | } 98 | 99 | func (c *Client) SaveWithMask() error { 100 | paths := []string{"id", "email", "address.city", "address.zipcode"} 101 | fm := fieldmaskpb.FieldMask{Paths: paths} 102 | req := &pb.UpdateRequest{ 103 | User: &pb.User{ 104 | Id: "001", 105 | Email: "alice_new@gmail.com", 106 | Address: &pb.Address{ 107 | City: "Ikebukuro", 108 | Zipcode: "170-0000", 109 | }, 110 | }, 111 | FieldMask: &fm, 112 | } 113 | _, err := c.cli.Update(context.Background(), req) 114 | if err != nil { 115 | return err 116 | } 117 | return nil 118 | } 119 | 120 | func (c *Client) Close() { 121 | c.conn.Close() 122 | } 123 | -------------------------------------------------------------------------------- /fieldmask/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | mongo: 4 | image: mongo:5.0.9 5 | ports: 6 | - "27017:27017" 7 | 8 | -------------------------------------------------------------------------------- /fieldmask/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jun06t/grpc-sample/fieldmask 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/chidiwilliams/flatbson v0.3.0 7 | github.com/golang/protobuf v1.5.2 8 | github.com/mennanov/fmutils v0.2.0 9 | go.mongodb.org/mongo-driver v1.9.1 10 | google.golang.org/grpc v1.53.0 11 | google.golang.org/protobuf v1.28.1 12 | ) 13 | 14 | require ( 15 | github.com/go-stack/stack v1.8.0 // indirect 16 | github.com/golang/snappy v0.0.1 // indirect 17 | github.com/klauspost/compress v1.13.6 // indirect 18 | github.com/pkg/errors v0.9.1 // indirect 19 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect 20 | github.com/xdg-go/scram v1.0.2 // indirect 21 | github.com/xdg-go/stringprep v1.0.2 // indirect 22 | github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect 23 | golang.org/x/crypto v0.31.0 // indirect 24 | golang.org/x/net v0.33.0 // indirect 25 | golang.org/x/sync v0.10.0 // indirect 26 | golang.org/x/sys v0.28.0 // indirect 27 | golang.org/x/text v0.21.0 // indirect 28 | google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect 29 | ) 30 | -------------------------------------------------------------------------------- /fieldmask/proto/user.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option go_package = "github.com/jun06t/grpc-sample/fieldmask/proto/go/user"; 4 | 5 | package user; 6 | 7 | import "google/protobuf/empty.proto"; 8 | import "google/protobuf/field_mask.proto"; 9 | 10 | service UserService { 11 | rpc Get(GetRequest) returns (GetReply) {} 12 | rpc Update(UpdateRequest) returns (google.protobuf.Empty) {} 13 | } 14 | 15 | message User { 16 | string id = 1; 17 | string name = 2; 18 | string email = 3; 19 | int64 age = 4; 20 | Address address = 5; 21 | } 22 | 23 | message Address { 24 | string country = 1; 25 | string state = 2; 26 | string city = 3; 27 | string zipcode = 4; 28 | } 29 | 30 | message GetRequest { 31 | string id = 1; 32 | google.protobuf.FieldMask field_mask = 2; 33 | } 34 | 35 | message GetReply { 36 | User user = 1; 37 | } 38 | 39 | message UpdateRequest { 40 | User user = 1; 41 | google.protobuf.FieldMask field_mask = 2; 42 | } 43 | -------------------------------------------------------------------------------- /fieldmask/server/entity.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type User struct { 4 | ID string `bson:"_id"` 5 | Name string `bson:"name,omitempty"` 6 | Email *string `bson:"email,omitempty"` 7 | Age int `bson:"age,omitempty"` 8 | Address Address `bson:"address,omitempty"` 9 | } 10 | 11 | type Address struct { 12 | Country string `bson:"country,omitempty"` 13 | State string `bson:"state,omitempty"` 14 | City string `bson:"city,omitempty"` 15 | Zipcode string `bson:"zipcode,omitempty"` 16 | } 17 | -------------------------------------------------------------------------------- /fieldmask/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net" 8 | 9 | "github.com/golang/protobuf/ptypes/empty" 10 | "github.com/mennanov/fmutils" 11 | "google.golang.org/grpc" 12 | "google.golang.org/grpc/codes" 13 | "google.golang.org/grpc/status" 14 | 15 | pb "github.com/jun06t/grpc-sample/fieldmask/proto/go/user" 16 | ) 17 | 18 | const ( 19 | port = ":8080" 20 | ) 21 | 22 | type server struct { 23 | mcli *mongoClient 24 | } 25 | 26 | func (s *server) Get(ctx context.Context, in *pb.GetRequest) (*pb.GetReply, error) { 27 | user, err := s.mcli.GetUser(ctx, in.Id) 28 | if err != nil { 29 | return nil, status.Error(codes.Internal, fmt.Sprintf("failed to get user: %s", err)) 30 | } 31 | resp := &pb.GetReply{ 32 | User: s.toUserProto(user), 33 | } 34 | if in.FieldMask != nil { 35 | in.FieldMask.Normalize() 36 | if in.FieldMask.IsValid(resp.User) { 37 | fmutils.Filter(resp.User, in.FieldMask.GetPaths()) 38 | } 39 | } 40 | return resp, nil 41 | } 42 | 43 | func (s *server) Update(ctx context.Context, in *pb.UpdateRequest) (*empty.Empty, error) { 44 | if in.FieldMask != nil { 45 | in.FieldMask.Normalize() 46 | if in.FieldMask.IsValid(in.User) { 47 | fmutils.Filter(in.User, in.FieldMask.GetPaths()) 48 | } 49 | } 50 | data := s.toUserEntity(in.User, in.FieldMask.GetPaths()) 51 | err := s.mcli.UpdateUser(ctx, data) 52 | if err != nil { 53 | return nil, status.Error(codes.Internal, fmt.Sprintf("failed to update user: %s", err)) 54 | } 55 | return &empty.Empty{}, nil 56 | } 57 | 58 | func main() { 59 | mcli, err := newClient(context.Background()) 60 | if err != nil { 61 | log.Fatal(err) 62 | } 63 | 64 | lis, err := net.Listen("tcp", port) 65 | if err != nil { 66 | log.Fatal(err) 67 | } 68 | s := grpc.NewServer() 69 | pb.RegisterUserServiceServer(s, &server{mcli}) 70 | err = s.Serve(lis) 71 | if err != nil { 72 | log.Fatal(err) 73 | } 74 | } 75 | 76 | func (s *server) toUserProto(in User) *pb.User { 77 | return &pb.User{ 78 | Id: in.ID, 79 | Name: in.Name, 80 | Age: int64(in.Age), 81 | Email: *in.Email, 82 | Address: &pb.Address{ 83 | Country: in.Address.Country, 84 | State: in.Address.State, 85 | City: in.Address.City, 86 | Zipcode: in.Address.Zipcode, 87 | }, 88 | } 89 | } 90 | 91 | func (s *server) toUserEntity(in *pb.User, paths []string) User { 92 | u := User{ 93 | ID: in.Id, 94 | Name: in.Name, 95 | Age: int(in.Age), 96 | Email: &in.Email, 97 | } 98 | if in.Address != nil { 99 | u.Address = Address{ 100 | Country: in.Address.Country, 101 | State: in.Address.State, 102 | City: in.Address.City, 103 | Zipcode: in.Address.Zipcode, 104 | } 105 | } 106 | if len(paths) == 0 { 107 | return u 108 | } 109 | 110 | // set nil to omit empty 111 | u.Email = nil 112 | 113 | for i := range paths { 114 | if paths[i] == "email" { 115 | u.Email = &in.Email 116 | } 117 | } 118 | return u 119 | } 120 | -------------------------------------------------------------------------------- /fieldmask/server/mongo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/chidiwilliams/flatbson" 7 | "go.mongodb.org/mongo-driver/bson" 8 | "go.mongodb.org/mongo-driver/mongo" 9 | "go.mongodb.org/mongo-driver/mongo/options" 10 | ) 11 | 12 | const ( 13 | dbName = "field_test" 14 | colName = "users" 15 | ) 16 | 17 | type mongoClient struct { 18 | cli *mongo.Client 19 | } 20 | 21 | func newClient(ctx context.Context) (*mongoClient, error) { 22 | client, err := mongo.Connect( 23 | ctx, 24 | options.Client().ApplyURI("mongodb://localhost:27017")) 25 | if err != nil { 26 | return nil, err 27 | } 28 | if err := client.Ping(ctx, nil); err != nil { 29 | return nil, err 30 | } 31 | 32 | return &mongoClient{client}, nil 33 | } 34 | 35 | func (m *mongoClient) GetUser(ctx context.Context, id string) (User, error) { 36 | col := m.cli.Database(dbName).Collection(colName) 37 | u := User{} 38 | err := col.FindOne(ctx, bson.M{"_id": id}).Decode(&u) 39 | if err != nil { 40 | return User{}, err 41 | } 42 | return u, nil 43 | } 44 | 45 | func (m *mongoClient) UpdateUser(ctx context.Context, u User) error { 46 | col := m.cli.Database(dbName).Collection(colName) 47 | opt := options.Update().SetUpsert(true) 48 | doc, err := flatbson.Flatten(u) 49 | if err != nil { 50 | return err 51 | } 52 | _, err = col.UpdateOne(ctx, bson.M{"_id": u.ID}, bson.M{ 53 | "$set": doc, 54 | }, opt) 55 | if err != nil { 56 | return err 57 | } 58 | return nil 59 | 60 | } 61 | -------------------------------------------------------------------------------- /go-package-option/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /go-package-option/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto_before proto_after proto_format clean 2 | 3 | BEFORE_PATH=before 4 | 5 | proto_before: proto_format 6 | protoc \ 7 | -I=./${BEFORE_PATH} \ 8 | --go_out=:./${BEFORE_PATH} \ 9 | ./${BEFORE_PATH}/team/*.proto \ 10 | ./${BEFORE_PATH}/person/*.proto 11 | 12 | AFTER_PATH=after 13 | 14 | proto_after: proto_format 15 | protoc \ 16 | -I=./${AFTER_PATH} \ 17 | --go_out=:./${AFTER_PATH} \ 18 | --go_opt=module=github.com/jun06t/grpc-sample/go-package-option/${AFTER_PATH} \ 19 | ./${AFTER_PATH}/team/*.proto \ 20 | ./${AFTER_PATH}/person/*.proto 21 | 22 | proto_format: 23 | find ./before -name "*.proto" | xargs clang-format -i 24 | find ./after -name "*.proto" | xargs clang-format -i 25 | 26 | clean: 27 | find ./before -name "*.pb.go" | xargs rm 28 | find ./after -name "*.pb.go" | xargs rm 29 | -------------------------------------------------------------------------------- /go-package-option/after/person/person.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // versions: 3 | // protoc-gen-go v1.23.0 4 | // protoc v3.14.0 5 | // source: person/person.proto 6 | 7 | package person 8 | 9 | import ( 10 | proto "github.com/golang/protobuf/proto" 11 | protoreflect "google.golang.org/protobuf/reflect/protoreflect" 12 | protoimpl "google.golang.org/protobuf/runtime/protoimpl" 13 | reflect "reflect" 14 | sync "sync" 15 | ) 16 | 17 | const ( 18 | // Verify that this generated code is sufficiently up-to-date. 19 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) 20 | // Verify that runtime/protoimpl is sufficiently up-to-date. 21 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) 22 | ) 23 | 24 | // This is a compile-time assertion that a sufficiently up-to-date version 25 | // of the legacy proto package is being used. 26 | const _ = proto.ProtoPackageIsVersion4 27 | 28 | type Person struct { 29 | state protoimpl.MessageState 30 | sizeCache protoimpl.SizeCache 31 | unknownFields protoimpl.UnknownFields 32 | 33 | Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` 34 | Age uint32 `protobuf:"varint,2,opt,name=Age,proto3" json:"Age,omitempty"` 35 | } 36 | 37 | func (x *Person) Reset() { 38 | *x = Person{} 39 | if protoimpl.UnsafeEnabled { 40 | mi := &file_person_person_proto_msgTypes[0] 41 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 42 | ms.StoreMessageInfo(mi) 43 | } 44 | } 45 | 46 | func (x *Person) String() string { 47 | return protoimpl.X.MessageStringOf(x) 48 | } 49 | 50 | func (*Person) ProtoMessage() {} 51 | 52 | func (x *Person) ProtoReflect() protoreflect.Message { 53 | mi := &file_person_person_proto_msgTypes[0] 54 | if protoimpl.UnsafeEnabled && x != nil { 55 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 56 | if ms.LoadMessageInfo() == nil { 57 | ms.StoreMessageInfo(mi) 58 | } 59 | return ms 60 | } 61 | return mi.MessageOf(x) 62 | } 63 | 64 | // Deprecated: Use Person.ProtoReflect.Descriptor instead. 65 | func (*Person) Descriptor() ([]byte, []int) { 66 | return file_person_person_proto_rawDescGZIP(), []int{0} 67 | } 68 | 69 | func (x *Person) GetName() string { 70 | if x != nil { 71 | return x.Name 72 | } 73 | return "" 74 | } 75 | 76 | func (x *Person) GetAge() uint32 { 77 | if x != nil { 78 | return x.Age 79 | } 80 | return 0 81 | } 82 | 83 | var File_person_person_proto protoreflect.FileDescriptor 84 | 85 | var file_person_person_proto_rawDesc = []byte{ 86 | 0x0a, 0x13, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2f, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2e, 87 | 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x22, 0x2e, 0x0a, 88 | 0x06, 0x50, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x18, 89 | 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x41, 90 | 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x03, 0x41, 0x67, 0x65, 0x42, 0x3e, 0x5a, 91 | 0x3c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6a, 0x75, 0x6e, 0x30, 92 | 0x36, 0x74, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2d, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2f, 0x67, 93 | 0x6f, 0x2d, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x2d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 94 | 0x2f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x2f, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x62, 0x06, 0x70, 95 | 0x72, 0x6f, 0x74, 0x6f, 0x33, 96 | } 97 | 98 | var ( 99 | file_person_person_proto_rawDescOnce sync.Once 100 | file_person_person_proto_rawDescData = file_person_person_proto_rawDesc 101 | ) 102 | 103 | func file_person_person_proto_rawDescGZIP() []byte { 104 | file_person_person_proto_rawDescOnce.Do(func() { 105 | file_person_person_proto_rawDescData = protoimpl.X.CompressGZIP(file_person_person_proto_rawDescData) 106 | }) 107 | return file_person_person_proto_rawDescData 108 | } 109 | 110 | var file_person_person_proto_msgTypes = make([]protoimpl.MessageInfo, 1) 111 | var file_person_person_proto_goTypes = []interface{}{ 112 | (*Person)(nil), // 0: person.Person 113 | } 114 | var file_person_person_proto_depIdxs = []int32{ 115 | 0, // [0:0] is the sub-list for method output_type 116 | 0, // [0:0] is the sub-list for method input_type 117 | 0, // [0:0] is the sub-list for extension type_name 118 | 0, // [0:0] is the sub-list for extension extendee 119 | 0, // [0:0] is the sub-list for field type_name 120 | } 121 | 122 | func init() { file_person_person_proto_init() } 123 | func file_person_person_proto_init() { 124 | if File_person_person_proto != nil { 125 | return 126 | } 127 | if !protoimpl.UnsafeEnabled { 128 | file_person_person_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { 129 | switch v := v.(*Person); i { 130 | case 0: 131 | return &v.state 132 | case 1: 133 | return &v.sizeCache 134 | case 2: 135 | return &v.unknownFields 136 | default: 137 | return nil 138 | } 139 | } 140 | } 141 | type x struct{} 142 | out := protoimpl.TypeBuilder{ 143 | File: protoimpl.DescBuilder{ 144 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(), 145 | RawDescriptor: file_person_person_proto_rawDesc, 146 | NumEnums: 0, 147 | NumMessages: 1, 148 | NumExtensions: 0, 149 | NumServices: 0, 150 | }, 151 | GoTypes: file_person_person_proto_goTypes, 152 | DependencyIndexes: file_person_person_proto_depIdxs, 153 | MessageInfos: file_person_person_proto_msgTypes, 154 | }.Build() 155 | File_person_person_proto = out.File 156 | file_person_person_proto_rawDesc = nil 157 | file_person_person_proto_goTypes = nil 158 | file_person_person_proto_depIdxs = nil 159 | } 160 | -------------------------------------------------------------------------------- /go-package-option/after/person/person.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option go_package = "github.com/jun06t/grpc-sample/go-package-option/after/person"; 4 | 5 | package person; 6 | 7 | message Person { 8 | string Name = 1; 9 | uint32 Age = 2; 10 | } 11 | -------------------------------------------------------------------------------- /go-package-option/after/team/team.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // versions: 3 | // protoc-gen-go v1.23.0 4 | // protoc v3.14.0 5 | // source: team/team.proto 6 | 7 | package team 8 | 9 | import ( 10 | proto "github.com/golang/protobuf/proto" 11 | person "github.com/jun06t/grpc-sample/go-package-option/after/person" 12 | protoreflect "google.golang.org/protobuf/reflect/protoreflect" 13 | protoimpl "google.golang.org/protobuf/runtime/protoimpl" 14 | reflect "reflect" 15 | sync "sync" 16 | ) 17 | 18 | const ( 19 | // Verify that this generated code is sufficiently up-to-date. 20 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) 21 | // Verify that runtime/protoimpl is sufficiently up-to-date. 22 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) 23 | ) 24 | 25 | // This is a compile-time assertion that a sufficiently up-to-date version 26 | // of the legacy proto package is being used. 27 | const _ = proto.ProtoPackageIsVersion4 28 | 29 | type Team struct { 30 | state protoimpl.MessageState 31 | sizeCache protoimpl.SizeCache 32 | unknownFields protoimpl.UnknownFields 33 | 34 | People []*person.Person `protobuf:"bytes,1,rep,name=people,proto3" json:"people,omitempty"` 35 | } 36 | 37 | func (x *Team) Reset() { 38 | *x = Team{} 39 | if protoimpl.UnsafeEnabled { 40 | mi := &file_team_team_proto_msgTypes[0] 41 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 42 | ms.StoreMessageInfo(mi) 43 | } 44 | } 45 | 46 | func (x *Team) String() string { 47 | return protoimpl.X.MessageStringOf(x) 48 | } 49 | 50 | func (*Team) ProtoMessage() {} 51 | 52 | func (x *Team) ProtoReflect() protoreflect.Message { 53 | mi := &file_team_team_proto_msgTypes[0] 54 | if protoimpl.UnsafeEnabled && x != nil { 55 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 56 | if ms.LoadMessageInfo() == nil { 57 | ms.StoreMessageInfo(mi) 58 | } 59 | return ms 60 | } 61 | return mi.MessageOf(x) 62 | } 63 | 64 | // Deprecated: Use Team.ProtoReflect.Descriptor instead. 65 | func (*Team) Descriptor() ([]byte, []int) { 66 | return file_team_team_proto_rawDescGZIP(), []int{0} 67 | } 68 | 69 | func (x *Team) GetPeople() []*person.Person { 70 | if x != nil { 71 | return x.People 72 | } 73 | return nil 74 | } 75 | 76 | var File_team_team_proto protoreflect.FileDescriptor 77 | 78 | var file_team_team_proto_rawDesc = []byte{ 79 | 0x0a, 0x0f, 0x74, 0x65, 0x61, 0x6d, 0x2f, 0x74, 0x65, 0x61, 0x6d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 80 | 0x6f, 0x12, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x1a, 0x13, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2f, 81 | 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2e, 0x0a, 0x04, 82 | 0x54, 0x65, 0x61, 0x6d, 0x12, 0x26, 0x0a, 0x06, 0x70, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x18, 0x01, 83 | 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2e, 0x50, 0x65, 84 | 0x72, 0x73, 0x6f, 0x6e, 0x52, 0x06, 0x70, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x42, 0x3c, 0x5a, 0x3a, 85 | 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6a, 0x75, 0x6e, 0x30, 0x36, 86 | 0x74, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2d, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2f, 0x67, 0x6f, 87 | 0x2d, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x2d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 88 | 0x61, 0x66, 0x74, 0x65, 0x72, 0x2f, 0x74, 0x65, 0x61, 0x6d, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 89 | 0x6f, 0x33, 90 | } 91 | 92 | var ( 93 | file_team_team_proto_rawDescOnce sync.Once 94 | file_team_team_proto_rawDescData = file_team_team_proto_rawDesc 95 | ) 96 | 97 | func file_team_team_proto_rawDescGZIP() []byte { 98 | file_team_team_proto_rawDescOnce.Do(func() { 99 | file_team_team_proto_rawDescData = protoimpl.X.CompressGZIP(file_team_team_proto_rawDescData) 100 | }) 101 | return file_team_team_proto_rawDescData 102 | } 103 | 104 | var file_team_team_proto_msgTypes = make([]protoimpl.MessageInfo, 1) 105 | var file_team_team_proto_goTypes = []interface{}{ 106 | (*Team)(nil), // 0: team.Team 107 | (*person.Person)(nil), // 1: person.Person 108 | } 109 | var file_team_team_proto_depIdxs = []int32{ 110 | 1, // 0: team.Team.people:type_name -> person.Person 111 | 1, // [1:1] is the sub-list for method output_type 112 | 1, // [1:1] is the sub-list for method input_type 113 | 1, // [1:1] is the sub-list for extension type_name 114 | 1, // [1:1] is the sub-list for extension extendee 115 | 0, // [0:1] is the sub-list for field type_name 116 | } 117 | 118 | func init() { file_team_team_proto_init() } 119 | func file_team_team_proto_init() { 120 | if File_team_team_proto != nil { 121 | return 122 | } 123 | if !protoimpl.UnsafeEnabled { 124 | file_team_team_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { 125 | switch v := v.(*Team); i { 126 | case 0: 127 | return &v.state 128 | case 1: 129 | return &v.sizeCache 130 | case 2: 131 | return &v.unknownFields 132 | default: 133 | return nil 134 | } 135 | } 136 | } 137 | type x struct{} 138 | out := protoimpl.TypeBuilder{ 139 | File: protoimpl.DescBuilder{ 140 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(), 141 | RawDescriptor: file_team_team_proto_rawDesc, 142 | NumEnums: 0, 143 | NumMessages: 1, 144 | NumExtensions: 0, 145 | NumServices: 0, 146 | }, 147 | GoTypes: file_team_team_proto_goTypes, 148 | DependencyIndexes: file_team_team_proto_depIdxs, 149 | MessageInfos: file_team_team_proto_msgTypes, 150 | }.Build() 151 | File_team_team_proto = out.File 152 | file_team_team_proto_rawDesc = nil 153 | file_team_team_proto_goTypes = nil 154 | file_team_team_proto_depIdxs = nil 155 | } 156 | -------------------------------------------------------------------------------- /go-package-option/after/team/team.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option go_package = "github.com/jun06t/grpc-sample/go-package-option/after/team"; 4 | 5 | package team; 6 | 7 | import "person/person.proto"; 8 | 9 | message Team { 10 | repeated person.Person people = 1; 11 | } 12 | -------------------------------------------------------------------------------- /go-package-option/before/person/person.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // versions: 3 | // protoc-gen-go v1.23.0 4 | // protoc v3.14.0 5 | // source: person/person.proto 6 | 7 | package person 8 | 9 | import ( 10 | proto "github.com/golang/protobuf/proto" 11 | protoreflect "google.golang.org/protobuf/reflect/protoreflect" 12 | protoimpl "google.golang.org/protobuf/runtime/protoimpl" 13 | reflect "reflect" 14 | sync "sync" 15 | ) 16 | 17 | const ( 18 | // Verify that this generated code is sufficiently up-to-date. 19 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) 20 | // Verify that runtime/protoimpl is sufficiently up-to-date. 21 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) 22 | ) 23 | 24 | // This is a compile-time assertion that a sufficiently up-to-date version 25 | // of the legacy proto package is being used. 26 | const _ = proto.ProtoPackageIsVersion4 27 | 28 | type Person struct { 29 | state protoimpl.MessageState 30 | sizeCache protoimpl.SizeCache 31 | unknownFields protoimpl.UnknownFields 32 | 33 | Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` 34 | Age uint32 `protobuf:"varint,2,opt,name=Age,proto3" json:"Age,omitempty"` 35 | } 36 | 37 | func (x *Person) Reset() { 38 | *x = Person{} 39 | if protoimpl.UnsafeEnabled { 40 | mi := &file_person_person_proto_msgTypes[0] 41 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 42 | ms.StoreMessageInfo(mi) 43 | } 44 | } 45 | 46 | func (x *Person) String() string { 47 | return protoimpl.X.MessageStringOf(x) 48 | } 49 | 50 | func (*Person) ProtoMessage() {} 51 | 52 | func (x *Person) ProtoReflect() protoreflect.Message { 53 | mi := &file_person_person_proto_msgTypes[0] 54 | if protoimpl.UnsafeEnabled && x != nil { 55 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 56 | if ms.LoadMessageInfo() == nil { 57 | ms.StoreMessageInfo(mi) 58 | } 59 | return ms 60 | } 61 | return mi.MessageOf(x) 62 | } 63 | 64 | // Deprecated: Use Person.ProtoReflect.Descriptor instead. 65 | func (*Person) Descriptor() ([]byte, []int) { 66 | return file_person_person_proto_rawDescGZIP(), []int{0} 67 | } 68 | 69 | func (x *Person) GetName() string { 70 | if x != nil { 71 | return x.Name 72 | } 73 | return "" 74 | } 75 | 76 | func (x *Person) GetAge() uint32 { 77 | if x != nil { 78 | return x.Age 79 | } 80 | return 0 81 | } 82 | 83 | var File_person_person_proto protoreflect.FileDescriptor 84 | 85 | var file_person_person_proto_rawDesc = []byte{ 86 | 0x0a, 0x13, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2f, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2e, 87 | 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x22, 0x2e, 0x0a, 88 | 0x06, 0x50, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x18, 89 | 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x41, 90 | 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x03, 0x41, 0x67, 0x65, 0x62, 0x06, 0x70, 91 | 0x72, 0x6f, 0x74, 0x6f, 0x33, 92 | } 93 | 94 | var ( 95 | file_person_person_proto_rawDescOnce sync.Once 96 | file_person_person_proto_rawDescData = file_person_person_proto_rawDesc 97 | ) 98 | 99 | func file_person_person_proto_rawDescGZIP() []byte { 100 | file_person_person_proto_rawDescOnce.Do(func() { 101 | file_person_person_proto_rawDescData = protoimpl.X.CompressGZIP(file_person_person_proto_rawDescData) 102 | }) 103 | return file_person_person_proto_rawDescData 104 | } 105 | 106 | var file_person_person_proto_msgTypes = make([]protoimpl.MessageInfo, 1) 107 | var file_person_person_proto_goTypes = []interface{}{ 108 | (*Person)(nil), // 0: person.Person 109 | } 110 | var file_person_person_proto_depIdxs = []int32{ 111 | 0, // [0:0] is the sub-list for method output_type 112 | 0, // [0:0] is the sub-list for method input_type 113 | 0, // [0:0] is the sub-list for extension type_name 114 | 0, // [0:0] is the sub-list for extension extendee 115 | 0, // [0:0] is the sub-list for field type_name 116 | } 117 | 118 | func init() { file_person_person_proto_init() } 119 | func file_person_person_proto_init() { 120 | if File_person_person_proto != nil { 121 | return 122 | } 123 | if !protoimpl.UnsafeEnabled { 124 | file_person_person_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { 125 | switch v := v.(*Person); i { 126 | case 0: 127 | return &v.state 128 | case 1: 129 | return &v.sizeCache 130 | case 2: 131 | return &v.unknownFields 132 | default: 133 | return nil 134 | } 135 | } 136 | } 137 | type x struct{} 138 | out := protoimpl.TypeBuilder{ 139 | File: protoimpl.DescBuilder{ 140 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(), 141 | RawDescriptor: file_person_person_proto_rawDesc, 142 | NumEnums: 0, 143 | NumMessages: 1, 144 | NumExtensions: 0, 145 | NumServices: 0, 146 | }, 147 | GoTypes: file_person_person_proto_goTypes, 148 | DependencyIndexes: file_person_person_proto_depIdxs, 149 | MessageInfos: file_person_person_proto_msgTypes, 150 | }.Build() 151 | File_person_person_proto = out.File 152 | file_person_person_proto_rawDesc = nil 153 | file_person_person_proto_goTypes = nil 154 | file_person_person_proto_depIdxs = nil 155 | } 156 | -------------------------------------------------------------------------------- /go-package-option/before/person/person.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package person; 4 | 5 | message Person { 6 | string Name = 1; 7 | uint32 Age = 2; 8 | } 9 | -------------------------------------------------------------------------------- /go-package-option/before/team/team.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // versions: 3 | // protoc-gen-go v1.23.0 4 | // protoc v3.14.0 5 | // source: team/team.proto 6 | 7 | package team 8 | 9 | import ( 10 | proto "github.com/golang/protobuf/proto" 11 | protoreflect "google.golang.org/protobuf/reflect/protoreflect" 12 | protoimpl "google.golang.org/protobuf/runtime/protoimpl" 13 | person "person" 14 | reflect "reflect" 15 | sync "sync" 16 | ) 17 | 18 | const ( 19 | // Verify that this generated code is sufficiently up-to-date. 20 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) 21 | // Verify that runtime/protoimpl is sufficiently up-to-date. 22 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) 23 | ) 24 | 25 | // This is a compile-time assertion that a sufficiently up-to-date version 26 | // of the legacy proto package is being used. 27 | const _ = proto.ProtoPackageIsVersion4 28 | 29 | type Team struct { 30 | state protoimpl.MessageState 31 | sizeCache protoimpl.SizeCache 32 | unknownFields protoimpl.UnknownFields 33 | 34 | People []*person.Person `protobuf:"bytes,1,rep,name=people,proto3" json:"people,omitempty"` 35 | } 36 | 37 | func (x *Team) Reset() { 38 | *x = Team{} 39 | if protoimpl.UnsafeEnabled { 40 | mi := &file_team_team_proto_msgTypes[0] 41 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 42 | ms.StoreMessageInfo(mi) 43 | } 44 | } 45 | 46 | func (x *Team) String() string { 47 | return protoimpl.X.MessageStringOf(x) 48 | } 49 | 50 | func (*Team) ProtoMessage() {} 51 | 52 | func (x *Team) ProtoReflect() protoreflect.Message { 53 | mi := &file_team_team_proto_msgTypes[0] 54 | if protoimpl.UnsafeEnabled && x != nil { 55 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 56 | if ms.LoadMessageInfo() == nil { 57 | ms.StoreMessageInfo(mi) 58 | } 59 | return ms 60 | } 61 | return mi.MessageOf(x) 62 | } 63 | 64 | // Deprecated: Use Team.ProtoReflect.Descriptor instead. 65 | func (*Team) Descriptor() ([]byte, []int) { 66 | return file_team_team_proto_rawDescGZIP(), []int{0} 67 | } 68 | 69 | func (x *Team) GetPeople() []*person.Person { 70 | if x != nil { 71 | return x.People 72 | } 73 | return nil 74 | } 75 | 76 | var File_team_team_proto protoreflect.FileDescriptor 77 | 78 | var file_team_team_proto_rawDesc = []byte{ 79 | 0x0a, 0x0f, 0x74, 0x65, 0x61, 0x6d, 0x2f, 0x74, 0x65, 0x61, 0x6d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 80 | 0x6f, 0x12, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x1a, 0x13, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2f, 81 | 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2e, 0x0a, 0x04, 82 | 0x54, 0x65, 0x61, 0x6d, 0x12, 0x26, 0x0a, 0x06, 0x70, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x18, 0x01, 83 | 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x70, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x2e, 0x50, 0x65, 84 | 0x72, 0x73, 0x6f, 0x6e, 0x52, 0x06, 0x70, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x62, 0x06, 0x70, 0x72, 85 | 0x6f, 0x74, 0x6f, 0x33, 86 | } 87 | 88 | var ( 89 | file_team_team_proto_rawDescOnce sync.Once 90 | file_team_team_proto_rawDescData = file_team_team_proto_rawDesc 91 | ) 92 | 93 | func file_team_team_proto_rawDescGZIP() []byte { 94 | file_team_team_proto_rawDescOnce.Do(func() { 95 | file_team_team_proto_rawDescData = protoimpl.X.CompressGZIP(file_team_team_proto_rawDescData) 96 | }) 97 | return file_team_team_proto_rawDescData 98 | } 99 | 100 | var file_team_team_proto_msgTypes = make([]protoimpl.MessageInfo, 1) 101 | var file_team_team_proto_goTypes = []interface{}{ 102 | (*Team)(nil), // 0: team.Team 103 | (*person.Person)(nil), // 1: person.Person 104 | } 105 | var file_team_team_proto_depIdxs = []int32{ 106 | 1, // 0: team.Team.people:type_name -> person.Person 107 | 1, // [1:1] is the sub-list for method output_type 108 | 1, // [1:1] is the sub-list for method input_type 109 | 1, // [1:1] is the sub-list for extension type_name 110 | 1, // [1:1] is the sub-list for extension extendee 111 | 0, // [0:1] is the sub-list for field type_name 112 | } 113 | 114 | func init() { file_team_team_proto_init() } 115 | func file_team_team_proto_init() { 116 | if File_team_team_proto != nil { 117 | return 118 | } 119 | if !protoimpl.UnsafeEnabled { 120 | file_team_team_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { 121 | switch v := v.(*Team); i { 122 | case 0: 123 | return &v.state 124 | case 1: 125 | return &v.sizeCache 126 | case 2: 127 | return &v.unknownFields 128 | default: 129 | return nil 130 | } 131 | } 132 | } 133 | type x struct{} 134 | out := protoimpl.TypeBuilder{ 135 | File: protoimpl.DescBuilder{ 136 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(), 137 | RawDescriptor: file_team_team_proto_rawDesc, 138 | NumEnums: 0, 139 | NumMessages: 1, 140 | NumExtensions: 0, 141 | NumServices: 0, 142 | }, 143 | GoTypes: file_team_team_proto_goTypes, 144 | DependencyIndexes: file_team_team_proto_depIdxs, 145 | MessageInfos: file_team_team_proto_msgTypes, 146 | }.Build() 147 | File_team_team_proto = out.File 148 | file_team_team_proto_rawDesc = nil 149 | file_team_team_proto_goTypes = nil 150 | file_team_team_proto_depIdxs = nil 151 | } 152 | -------------------------------------------------------------------------------- /go-package-option/before/team/team.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package team; 4 | 5 | import "person/person.proto"; 6 | 7 | message Team { 8 | repeated person.Person people = 1; 9 | } 10 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jun06t/grpc-sample 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/golang/protobuf v1.5.2 7 | github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 8 | github.com/grpc-ecosystem/grpc-gateway v1.16.0 9 | github.com/lithammer/shortuuid v3.0.0+incompatible 10 | golang.org/x/net v0.7.0 // indirect 11 | google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f 12 | google.golang.org/grpc v1.53.0 13 | google.golang.org/protobuf v1.28.1 14 | ) 15 | -------------------------------------------------------------------------------- /graceful/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /graceful/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /graceful/README.md: -------------------------------------------------------------------------------- 1 | # Unary(Simple) gRPC sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | go run client/main.go 16 | ``` 17 | 18 | Then it returns 19 | ``` 20 | 2017/11/14 14:31:42 Reply: Hello alice 21 | ``` 22 | -------------------------------------------------------------------------------- /graceful/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | pb "github.com/jun06t/grpc-sample/graceful/proto" 8 | "google.golang.org/grpc" 9 | ) 10 | 11 | const ( 12 | address = "localhost:8080" 13 | ) 14 | 15 | func main() { 16 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer conn.Close() 21 | 22 | c := pb.NewGreeterClient(conn) 23 | 24 | req := &pb.HelloRequest{ 25 | Name: "alice", 26 | } 27 | resp, err := c.SayHello(context.Background(), req) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | log.Println("Reply: ", resp.Message) 32 | } 33 | -------------------------------------------------------------------------------- /graceful/proto/helloworld.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: helloworld.proto 3 | 4 | package helloworld 5 | 6 | import ( 7 | context "context" 8 | fmt "fmt" 9 | proto "github.com/golang/protobuf/proto" 10 | grpc "google.golang.org/grpc" 11 | codes "google.golang.org/grpc/codes" 12 | status "google.golang.org/grpc/status" 13 | math "math" 14 | ) 15 | 16 | // Reference imports to suppress errors if they are not otherwise used. 17 | var _ = proto.Marshal 18 | var _ = fmt.Errorf 19 | var _ = math.Inf 20 | 21 | // This is a compile-time assertion to ensure that this generated file 22 | // is compatible with the proto package it is being compiled against. 23 | // A compilation error at this line likely means your copy of the 24 | // proto package needs to be updated. 25 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 26 | 27 | type HelloRequest struct { 28 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 29 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 30 | XXX_unrecognized []byte `json:"-"` 31 | XXX_sizecache int32 `json:"-"` 32 | } 33 | 34 | func (m *HelloRequest) Reset() { *m = HelloRequest{} } 35 | func (m *HelloRequest) String() string { return proto.CompactTextString(m) } 36 | func (*HelloRequest) ProtoMessage() {} 37 | func (*HelloRequest) Descriptor() ([]byte, []int) { 38 | return fileDescriptor_17b8c58d586b62f2, []int{0} 39 | } 40 | 41 | func (m *HelloRequest) XXX_Unmarshal(b []byte) error { 42 | return xxx_messageInfo_HelloRequest.Unmarshal(m, b) 43 | } 44 | func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 45 | return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic) 46 | } 47 | func (m *HelloRequest) XXX_Merge(src proto.Message) { 48 | xxx_messageInfo_HelloRequest.Merge(m, src) 49 | } 50 | func (m *HelloRequest) XXX_Size() int { 51 | return xxx_messageInfo_HelloRequest.Size(m) 52 | } 53 | func (m *HelloRequest) XXX_DiscardUnknown() { 54 | xxx_messageInfo_HelloRequest.DiscardUnknown(m) 55 | } 56 | 57 | var xxx_messageInfo_HelloRequest proto.InternalMessageInfo 58 | 59 | func (m *HelloRequest) GetName() string { 60 | if m != nil { 61 | return m.Name 62 | } 63 | return "" 64 | } 65 | 66 | type HelloReply struct { 67 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` 68 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 69 | XXX_unrecognized []byte `json:"-"` 70 | XXX_sizecache int32 `json:"-"` 71 | } 72 | 73 | func (m *HelloReply) Reset() { *m = HelloReply{} } 74 | func (m *HelloReply) String() string { return proto.CompactTextString(m) } 75 | func (*HelloReply) ProtoMessage() {} 76 | func (*HelloReply) Descriptor() ([]byte, []int) { 77 | return fileDescriptor_17b8c58d586b62f2, []int{1} 78 | } 79 | 80 | func (m *HelloReply) XXX_Unmarshal(b []byte) error { 81 | return xxx_messageInfo_HelloReply.Unmarshal(m, b) 82 | } 83 | func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 84 | return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) 85 | } 86 | func (m *HelloReply) XXX_Merge(src proto.Message) { 87 | xxx_messageInfo_HelloReply.Merge(m, src) 88 | } 89 | func (m *HelloReply) XXX_Size() int { 90 | return xxx_messageInfo_HelloReply.Size(m) 91 | } 92 | func (m *HelloReply) XXX_DiscardUnknown() { 93 | xxx_messageInfo_HelloReply.DiscardUnknown(m) 94 | } 95 | 96 | var xxx_messageInfo_HelloReply proto.InternalMessageInfo 97 | 98 | func (m *HelloReply) GetMessage() string { 99 | if m != nil { 100 | return m.Message 101 | } 102 | return "" 103 | } 104 | 105 | func init() { 106 | proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") 107 | proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") 108 | } 109 | 110 | func init() { proto.RegisterFile("helloworld.proto", fileDescriptor_17b8c58d586b62f2) } 111 | 112 | var fileDescriptor_17b8c58d586b62f2 = []byte{ 113 | // 141 bytes of a gzipped FileDescriptorProto 114 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0x48, 0xcd, 0xc9, 115 | 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, 116 | 0x28, 0x29, 0x71, 0xf1, 0x78, 0x80, 0x78, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0x42, 117 | 0x5c, 0x2c, 0x79, 0x89, 0xb9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x92, 118 | 0x1a, 0x17, 0x17, 0x54, 0x4d, 0x41, 0x4e, 0xa5, 0x90, 0x04, 0x17, 0x7b, 0x6e, 0x6a, 0x71, 0x71, 119 | 0x62, 0x3a, 0x4c, 0x11, 0x8c, 0x6b, 0xe4, 0xc9, 0xc5, 0xee, 0x5e, 0x94, 0x9a, 0x5a, 0x92, 0x5a, 120 | 0x24, 0x64, 0xc7, 0xc5, 0x11, 0x9c, 0x58, 0x09, 0xd6, 0x25, 0x24, 0xa1, 0x87, 0xe4, 0x02, 0x64, 121 | 0xcb, 0xa4, 0xc4, 0xb0, 0xc8, 0x14, 0xe4, 0x54, 0x2a, 0x31, 0x24, 0xb1, 0x81, 0x5d, 0x6a, 0x0c, 122 | 0x08, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x53, 0x4e, 0xf7, 0xbd, 0x00, 0x00, 0x00, 123 | } 124 | 125 | // Reference imports to suppress errors if they are not otherwise used. 126 | var _ context.Context 127 | var _ grpc.ClientConn 128 | 129 | // This is a compile-time assertion to ensure that this generated file 130 | // is compatible with the grpc package it is being compiled against. 131 | const _ = grpc.SupportPackageIsVersion4 132 | 133 | // GreeterClient is the client API for Greeter service. 134 | // 135 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. 136 | type GreeterClient interface { 137 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 138 | } 139 | 140 | type greeterClient struct { 141 | cc *grpc.ClientConn 142 | } 143 | 144 | func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { 145 | return &greeterClient{cc} 146 | } 147 | 148 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 149 | out := new(HelloReply) 150 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 151 | if err != nil { 152 | return nil, err 153 | } 154 | return out, nil 155 | } 156 | 157 | // GreeterServer is the server API for Greeter service. 158 | type GreeterServer interface { 159 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 160 | } 161 | 162 | // UnimplementedGreeterServer can be embedded to have forward compatible implementations. 163 | type UnimplementedGreeterServer struct { 164 | } 165 | 166 | func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) { 167 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 168 | } 169 | 170 | func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { 171 | s.RegisterService(&_Greeter_serviceDesc, srv) 172 | } 173 | 174 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 175 | in := new(HelloRequest) 176 | if err := dec(in); err != nil { 177 | return nil, err 178 | } 179 | if interceptor == nil { 180 | return srv.(GreeterServer).SayHello(ctx, in) 181 | } 182 | info := &grpc.UnaryServerInfo{ 183 | Server: srv, 184 | FullMethod: "/helloworld.Greeter/SayHello", 185 | } 186 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 187 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 188 | } 189 | return interceptor(ctx, in, info, handler) 190 | } 191 | 192 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 193 | ServiceName: "helloworld.Greeter", 194 | HandlerType: (*GreeterServer)(nil), 195 | Methods: []grpc.MethodDesc{ 196 | { 197 | MethodName: "SayHello", 198 | Handler: _Greeter_SayHello_Handler, 199 | }, 200 | }, 201 | Streams: []grpc.StreamDesc{}, 202 | Metadata: "helloworld.proto", 203 | } 204 | -------------------------------------------------------------------------------- /graceful/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | service Greeter { 6 | rpc SayHello(HelloRequest) returns (HelloReply) {} 7 | } 8 | 9 | message HelloRequest { 10 | string name = 1; 11 | } 12 | 13 | message HelloReply { 14 | string message = 1; 15 | } 16 | -------------------------------------------------------------------------------- /graceful/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net" 8 | "os" 9 | "os/signal" 10 | "syscall" 11 | "time" 12 | 13 | pb "github.com/jun06t/grpc-sample/graceful/proto" 14 | "google.golang.org/grpc" 15 | ) 16 | 17 | const ( 18 | port = ":8080" 19 | ) 20 | 21 | type server struct{} 22 | 23 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 24 | go func() { 25 | fmt.Println("service called") 26 | <-ctx.Done() 27 | fmt.Println("ctx done") 28 | }() 29 | time.Sleep(5 * time.Second) 30 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 31 | } 32 | 33 | func main() { 34 | lis, err := net.Listen("tcp", port) 35 | if err != nil { 36 | log.Fatal(err) 37 | } 38 | 39 | s := grpc.NewServer() 40 | pb.RegisterGreeterServer(s, &server{}) 41 | go func() { 42 | err = s.Serve(lis) 43 | if err != nil { 44 | log.Fatal(err) 45 | } 46 | }() 47 | 48 | quit := make(chan os.Signal, 1) 49 | signal.Notify(quit, syscall.SIGTERM, os.Interrupt) 50 | 51 | log.Printf("SIGNAL %d received, then shutting down...\n", <-quit) 52 | s.GracefulStop() 53 | //s.Stop() 54 | log.Println("server stopped") 55 | } 56 | -------------------------------------------------------------------------------- /grpc-gateway/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /grpc-gateway/Dockerfile-gateway: -------------------------------------------------------------------------------- 1 | FROM golang:1.10-alpine 2 | 3 | ARG REPO="github.com/jun06t/grpc-sample/grpc-gateway" 4 | 5 | RUN mkdir -p /go/src/${REPO} 6 | COPY . /go/src/${REPO} 7 | 8 | WORKDIR /go/src/${REPO} 9 | 10 | RUN go build -o grpc-gateway ./gateway/main.go && \ 11 | mv grpc-gateway /usr/local/bin/ 12 | 13 | EXPOSE 3000 14 | 15 | CMD ["grpc-gateway"] 16 | -------------------------------------------------------------------------------- /grpc-gateway/Dockerfile-grpc: -------------------------------------------------------------------------------- 1 | FROM golang:1.10-alpine 2 | 3 | ARG REPO="github.com/jun06t/grpc-sample/grpc-gateway" 4 | 5 | RUN mkdir -p /go/src/${REPO} 6 | COPY . /go/src/${REPO} 7 | 8 | WORKDIR /go/src/${REPO} 9 | 10 | RUN go build -o grpc-backend ./server/main.go && \ 11 | mv grpc-backend /usr/local/bin/ 12 | 13 | EXPOSE 8080 14 | 15 | CMD ["grpc-backend"] 16 | -------------------------------------------------------------------------------- /grpc-gateway/Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/golang/protobuf" 6 | packages = [ 7 | "jsonpb", 8 | "proto", 9 | "protoc-gen-go/descriptor", 10 | "ptypes", 11 | "ptypes/any", 12 | "ptypes/duration", 13 | "ptypes/struct", 14 | "ptypes/timestamp" 15 | ] 16 | revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" 17 | version = "v1.1.0" 18 | 19 | [[projects]] 20 | name = "github.com/grpc-ecosystem/grpc-gateway" 21 | packages = [ 22 | "runtime", 23 | "runtime/internal", 24 | "utilities" 25 | ] 26 | revision = "92583770e3f01b09a0d3e9bdf64321d8bebd48f2" 27 | version = "v1.4.1" 28 | 29 | [[projects]] 30 | branch = "master" 31 | name = "golang.org/x/net" 32 | packages = [ 33 | "context", 34 | "http/httpguts", 35 | "http2", 36 | "http2/hpack", 37 | "idna", 38 | "internal/timeseries", 39 | "trace" 40 | ] 41 | revision = "97aa3a539ec716117a9d15a4659a911f50d13c3c" 42 | 43 | [[projects]] 44 | name = "golang.org/x/text" 45 | packages = [ 46 | "collate", 47 | "collate/build", 48 | "internal/colltab", 49 | "internal/gen", 50 | "internal/tag", 51 | "internal/triegen", 52 | "internal/ucd", 53 | "language", 54 | "secure/bidirule", 55 | "transform", 56 | "unicode/bidi", 57 | "unicode/cldr", 58 | "unicode/norm", 59 | "unicode/rangetable" 60 | ] 61 | revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" 62 | version = "v0.3.0" 63 | 64 | [[projects]] 65 | branch = "master" 66 | name = "google.golang.org/genproto" 67 | packages = [ 68 | "googleapis/api/annotations", 69 | "googleapis/rpc/status" 70 | ] 71 | revision = "ff3583edef7de132f219f0efc00e097cabcc0ec0" 72 | 73 | [[projects]] 74 | name = "google.golang.org/grpc" 75 | packages = [ 76 | ".", 77 | "balancer", 78 | "balancer/base", 79 | "balancer/roundrobin", 80 | "codes", 81 | "connectivity", 82 | "credentials", 83 | "encoding", 84 | "encoding/proto", 85 | "grpclog", 86 | "internal", 87 | "internal/backoff", 88 | "internal/channelz", 89 | "internal/grpcrand", 90 | "keepalive", 91 | "metadata", 92 | "naming", 93 | "peer", 94 | "resolver", 95 | "resolver/dns", 96 | "resolver/passthrough", 97 | "stats", 98 | "status", 99 | "tap", 100 | "transport" 101 | ] 102 | revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" 103 | version = "v1.13.0" 104 | 105 | [solve-meta] 106 | analyzer-name = "dep" 107 | analyzer-version = 1 108 | inputs-digest = "b01280c8f99d0e9fac2829c13bfd2db7584bf9b1b2b3348a91a92d5732845bcb" 109 | solver-name = "gps-cdcl" 110 | solver-version = 1 111 | -------------------------------------------------------------------------------- /grpc-gateway/Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | name = "github.com/golang/protobuf" 30 | version = "1.1.0" 31 | 32 | [[constraint]] 33 | name = "github.com/grpc-ecosystem/grpc-gateway" 34 | version = "1.4.1" 35 | 36 | [[constraint]] 37 | branch = "master" 38 | name = "golang.org/x/net" 39 | 40 | [[constraint]] 41 | branch = "master" 42 | name = "google.golang.org/genproto" 43 | 44 | [[constraint]] 45 | name = "google.golang.org/grpc" 46 | version = "1.13.0" 47 | 48 | [prune] 49 | go-tests = true 50 | unused-packages = true 51 | -------------------------------------------------------------------------------- /grpc-gateway/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: prepare build proto 2 | 3 | REGISTRY_DOMAIN := jun06t 4 | 5 | prepare: 6 | dep ensure -v 7 | 8 | build: 9 | docker build -f Dockerfile-gateway -t ${REGISTRY_DOMAIN}/grpc-gateway:latest . 10 | docker build -f Dockerfile-grpc -t ${REGISTRY_DOMAIN}/grpc-backend:latest . 11 | 12 | push: 13 | docker push ${REGISTRY_DOMAIN}/grpc-gateway 14 | docker push ${REGISTRY_DOMAIN}/grpc-backend 15 | 16 | proto: 17 | protoc \ 18 | -I=./proto \ 19 | -I=${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ 20 | --go_out=plugins=grpc:./proto \ 21 | --grpc-gateway_out=logtostderr=true:./proto \ 22 | ./proto/*.proto 23 | -------------------------------------------------------------------------------- /grpc-gateway/README.md: -------------------------------------------------------------------------------- 1 | # gRPC Gateway sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRPC Gateway 14 | ``` 15 | go run gateway/main.go 16 | ``` 17 | 18 | ## Send Request 19 | ### Alive 20 | ``` 21 | curl http://localhost:3000/alive 22 | ``` 23 | 24 | This returns 25 | ``` 26 | {"status":true} 27 | ``` 28 | 29 | ### Get User 30 | ``` 31 | curl http://localhost:3000/user/100 32 | ``` 33 | 34 | This returns 35 | ``` 36 | {"id":"100","name":"Alice","age":20} 37 | ``` 38 | 39 | ### Get Users By Group 40 | ``` 41 | curl http://localhost:3000/user?group=ADMIN 42 | ``` 43 | 44 | This returns 45 | ``` 46 | {"group":"ADMIN","users":[{"name":"Alice","age":20},{"name":"Bob","age":24}]} 47 | ``` 48 | 49 | ### Update User 50 | ``` 51 | curl -XPUT http://localhost:3000/user/100 -d '{"name": "bob", "age": 16}' 52 | ``` 53 | 54 | Then the grpc server's stdout shows 55 | ``` 56 | 2017/11/14 14:25:52 update body is {id: 100, name: bob, age: 16} 57 | ``` 58 | -------------------------------------------------------------------------------- /grpc-gateway/gateway/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | _ "net/http/pprof" 8 | "os" 9 | 10 | "github.com/grpc-ecosystem/grpc-gateway/runtime" 11 | pb "github.com/jun06t/grpc-sample/grpc-gateway/proto" 12 | "google.golang.org/grpc" 13 | ) 14 | 15 | var ( 16 | endpoint = "localhost:8080" 17 | listenAddr = ":3000" 18 | ) 19 | 20 | func init() { 21 | ep := os.Getenv("ENDPOINT") 22 | if ep != "" { 23 | endpoint = ep 24 | } 25 | } 26 | 27 | func newGateway(ctx context.Context, opts ...runtime.ServeMuxOption) (http.Handler, error) { 28 | mux := runtime.NewServeMux(opts...) 29 | dialOpts := []grpc.DialOption{grpc.WithInsecure()} 30 | 31 | fmt.Println("Endpoint: ", endpoint) 32 | conn, err := grpc.Dial(endpoint, dialOpts...) 33 | if err != nil { 34 | return nil, err 35 | } 36 | err = pb.RegisterAliveServiceHandler(ctx, mux, conn) 37 | if err != nil { 38 | return nil, err 39 | } 40 | err = pb.RegisterUserServiceHandler(ctx, mux, conn) 41 | if err != nil { 42 | return nil, err 43 | } 44 | 45 | return mux, nil 46 | } 47 | 48 | // Run starts a HTTP server and blocks forever if successful. 49 | func Run(address string, opts ...runtime.ServeMuxOption) error { 50 | ctx := context.Background() 51 | ctx, cancel := context.WithCancel(ctx) 52 | defer cancel() 53 | 54 | gw, err := newGateway(ctx, opts...) 55 | if err != nil { 56 | return err 57 | } 58 | 59 | return http.ListenAndServe(address, gw) 60 | } 61 | 62 | func main() { 63 | fmt.Println("Listen Address:", listenAddr) 64 | if err := Run(listenAddr); err != nil { 65 | panic(err) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /grpc-gateway/proto/alive.pb.gw.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. 2 | // source: alive.proto 3 | 4 | /* 5 | Package gateway is a reverse proxy. 6 | 7 | It translates gRPC into RESTful JSON APIs. 8 | */ 9 | package gateway 10 | 11 | import ( 12 | "context" 13 | "io" 14 | "net/http" 15 | 16 | "github.com/golang/protobuf/proto" 17 | "github.com/grpc-ecosystem/grpc-gateway/runtime" 18 | "github.com/grpc-ecosystem/grpc-gateway/utilities" 19 | "google.golang.org/grpc" 20 | "google.golang.org/grpc/codes" 21 | "google.golang.org/grpc/grpclog" 22 | "google.golang.org/grpc/status" 23 | ) 24 | 25 | var _ codes.Code 26 | var _ io.Reader 27 | var _ status.Status 28 | var _ = runtime.String 29 | var _ = utilities.NewDoubleArray 30 | 31 | func request_AliveService_GetStatus_0(ctx context.Context, marshaler runtime.Marshaler, client AliveServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { 32 | var protoReq Empty 33 | var metadata runtime.ServerMetadata 34 | 35 | msg, err := client.GetStatus(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) 36 | return msg, metadata, err 37 | 38 | } 39 | 40 | func local_request_AliveService_GetStatus_0(ctx context.Context, marshaler runtime.Marshaler, server AliveServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { 41 | var protoReq Empty 42 | var metadata runtime.ServerMetadata 43 | 44 | msg, err := server.GetStatus(ctx, &protoReq) 45 | return msg, metadata, err 46 | 47 | } 48 | 49 | // RegisterAliveServiceHandlerServer registers the http handlers for service AliveService to "mux". 50 | // UnaryRPC :call AliveServiceServer directly. 51 | // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. 52 | func RegisterAliveServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server AliveServiceServer) error { 53 | 54 | mux.Handle("GET", pattern_AliveService_GetStatus_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { 55 | ctx, cancel := context.WithCancel(req.Context()) 56 | defer cancel() 57 | inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) 58 | rctx, err := runtime.AnnotateContext(ctx, mux, req) 59 | if err != nil { 60 | runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) 61 | return 62 | } 63 | resp, md, err := local_request_AliveService_GetStatus_0(rctx, inboundMarshaler, server, req, pathParams) 64 | ctx = runtime.NewServerMetadataContext(ctx, md) 65 | if err != nil { 66 | runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) 67 | return 68 | } 69 | 70 | forward_AliveService_GetStatus_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) 71 | 72 | }) 73 | 74 | return nil 75 | } 76 | 77 | // RegisterAliveServiceHandlerFromEndpoint is same as RegisterAliveServiceHandler but 78 | // automatically dials to "endpoint" and closes the connection when "ctx" gets done. 79 | func RegisterAliveServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { 80 | conn, err := grpc.Dial(endpoint, opts...) 81 | if err != nil { 82 | return err 83 | } 84 | defer func() { 85 | if err != nil { 86 | if cerr := conn.Close(); cerr != nil { 87 | grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) 88 | } 89 | return 90 | } 91 | go func() { 92 | <-ctx.Done() 93 | if cerr := conn.Close(); cerr != nil { 94 | grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) 95 | } 96 | }() 97 | }() 98 | 99 | return RegisterAliveServiceHandler(ctx, mux, conn) 100 | } 101 | 102 | // RegisterAliveServiceHandler registers the http handlers for service AliveService to "mux". 103 | // The handlers forward requests to the grpc endpoint over "conn". 104 | func RegisterAliveServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { 105 | return RegisterAliveServiceHandlerClient(ctx, mux, NewAliveServiceClient(conn)) 106 | } 107 | 108 | // RegisterAliveServiceHandlerClient registers the http handlers for service AliveService 109 | // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "AliveServiceClient". 110 | // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "AliveServiceClient" 111 | // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in 112 | // "AliveServiceClient" to call the correct interceptors. 113 | func RegisterAliveServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client AliveServiceClient) error { 114 | 115 | mux.Handle("GET", pattern_AliveService_GetStatus_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { 116 | ctx, cancel := context.WithCancel(req.Context()) 117 | defer cancel() 118 | inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) 119 | rctx, err := runtime.AnnotateContext(ctx, mux, req) 120 | if err != nil { 121 | runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) 122 | return 123 | } 124 | resp, md, err := request_AliveService_GetStatus_0(rctx, inboundMarshaler, client, req, pathParams) 125 | ctx = runtime.NewServerMetadataContext(ctx, md) 126 | if err != nil { 127 | runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) 128 | return 129 | } 130 | 131 | forward_AliveService_GetStatus_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) 132 | 133 | }) 134 | 135 | return nil 136 | } 137 | 138 | var ( 139 | pattern_AliveService_GetStatus_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"alive"}, "", runtime.AssumeColonVerbOpt(true))) 140 | ) 141 | 142 | var ( 143 | forward_AliveService_GetStatus_0 = runtime.ForwardResponseMessage 144 | ) 145 | -------------------------------------------------------------------------------- /grpc-gateway/proto/alive.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | import "google/api/annotations.proto"; 4 | 5 | package gateway; 6 | 7 | service AliveService { 8 | rpc GetStatus(Empty) returns (AliveResponse) { 9 | option (google.api.http) = { 10 | get: "/alive" 11 | }; 12 | } 13 | } 14 | 15 | message Empty {} 16 | 17 | message AliveResponse { 18 | bool status = 1; 19 | } 20 | -------------------------------------------------------------------------------- /grpc-gateway/proto/user.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | import "google/api/annotations.proto"; 4 | import "alive.proto"; 5 | 6 | package gateway; 7 | 8 | service UserService { 9 | rpc GetUser(GetUserRequest) returns (UserResponse) { 10 | option (google.api.http) = { 11 | get: "/user/{id}" 12 | }; 13 | } 14 | 15 | rpc GetUsersByGroup(UserGroupRequest) returns (UsersResponse) { 16 | option (google.api.http) = { 17 | get: "/user" 18 | }; 19 | } 20 | 21 | rpc UpdateUser(UpdateUserRequest) returns (Empty) { 22 | option (google.api.http) = { 23 | put: "/user/{id}" 24 | body: "*" 25 | }; 26 | } 27 | } 28 | 29 | message GetUserRequest { 30 | string id = 1; 31 | } 32 | 33 | message UpdateUserRequest { 34 | string id = 1; 35 | string name = 2; 36 | int32 age = 3; 37 | } 38 | 39 | message UserResponse { 40 | string id = 1; 41 | string name = 2; 42 | int32 age = 3; 43 | } 44 | 45 | enum Group { 46 | USER = 0; 47 | ADMIN = 1; 48 | DEVELOPER = 2; 49 | } 50 | 51 | message UserGroupRequest { 52 | Group group = 1; 53 | } 54 | 55 | message UsersResponse { 56 | Group group = 1; 57 | repeated UserResponse users = 2; 58 | } 59 | -------------------------------------------------------------------------------- /grpc-gateway/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net" 8 | 9 | pb "github.com/jun06t/grpc-sample/grpc-gateway/proto" 10 | "google.golang.org/grpc" 11 | ) 12 | 13 | const ( 14 | port = ":8080" 15 | ) 16 | 17 | type aliveService struct{} 18 | 19 | func (s *aliveService) GetStatus(ctx context.Context, in *pb.Empty) (*pb.AliveResponse, error) { 20 | return &pb.AliveResponse{Status: true}, nil 21 | } 22 | 23 | type userService struct{} 24 | 25 | func (s *userService) GetUser(ctx context.Context, in *pb.GetUserRequest) (*pb.UserResponse, error) { 26 | return &pb.UserResponse{ 27 | Id: in.Id, 28 | Name: "Alice", 29 | Age: 20, 30 | }, nil 31 | } 32 | 33 | func (s *userService) GetUsersByGroup(ctx context.Context, in *pb.UserGroupRequest) (*pb.UsersResponse, error) { 34 | return &pb.UsersResponse{ 35 | Group: in.Group, 36 | Users: []*pb.UserResponse{ 37 | {Name: "Alice", Age: 20}, 38 | {Name: "Bob", Age: 24}, 39 | }, 40 | }, nil 41 | } 42 | 43 | func (s *userService) UpdateUser(ctx context.Context, in *pb.UpdateUserRequest) (*pb.Empty, error) { 44 | log.Printf("update body is {id: %s, name: %s, age: %d}\n", in.Id, in.Name, in.Age) 45 | return &pb.Empty{}, nil 46 | } 47 | 48 | func main() { 49 | fmt.Println("Listen Address:", port) 50 | lis, err := net.Listen("tcp", port) 51 | if err != nil { 52 | log.Fatal(err) 53 | } 54 | 55 | s := grpc.NewServer() 56 | pb.RegisterAliveServiceServer(s, new(aliveService)) 57 | pb.RegisterUserServiceServer(s, new(userService)) 58 | err = s.Serve(lis) 59 | if err != nil { 60 | log.Fatal(err) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /image-proxy/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /image-proxy/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /image-proxy/README.md: -------------------------------------------------------------------------------- 1 | # Image proxy sample 2 | 3 | This is a proxy to convert jpeg/png to webp. 4 | 5 | ## Compile 6 | ``` 7 | $ make proto 8 | ``` 9 | 10 | ## Prepare 11 | You should install webp tool because this proxy runs ``cwebp`` command directly. 12 | ``` 13 | $ brew install webp 14 | ``` 15 | 16 | ## Run gRPC server 17 | ``` 18 | $ cd server 19 | $ go run main.go 20 | ``` 21 | 22 | ## Run gRRC Client 23 | ``` 24 | $ cd client 25 | $ go run main.go 26 | ``` 27 | 28 | Then you'll get webp image on client directory. 29 | ``` 30 | $ ls 31 | 001.webp main.go testimage.png 32 | ``` 33 | -------------------------------------------------------------------------------- /image-proxy/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io" 7 | "log" 8 | "os" 9 | 10 | pb "github.com/jun06t/grpc-sample/image-proxy/proto" 11 | "google.golang.org/grpc" 12 | ) 13 | 14 | const ( 15 | address = "localhost:8080" 16 | ) 17 | 18 | func main() { 19 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | defer conn.Close() 24 | 25 | client := pb.NewConverterClient(conn) 26 | 27 | file, err := os.Open("testimage.png") 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | defer file.Close() 32 | 33 | err = convert(client, file, "001") 34 | if err != nil { 35 | log.Fatal(err) 36 | } 37 | } 38 | 39 | func convert(client pb.ConverterClient, src io.Reader, name string) error { 40 | stream, err := client.Convert(context.Background()) 41 | if err != nil { 42 | return err 43 | } 44 | err = send(stream, src, name) 45 | if err != nil { 46 | return err 47 | } 48 | 49 | dst, err := os.Create(fmt.Sprintf("%s.webp", name)) 50 | if err != nil { 51 | return err 52 | } 53 | defer dst.Close() 54 | 55 | err = receive(stream, dst) 56 | if err != nil { 57 | return err 58 | } 59 | 60 | return nil 61 | } 62 | 63 | const ( 64 | bufSize = 1024 65 | ) 66 | 67 | func send(stream pb.Converter_ConvertClient, src io.Reader, id string) error { 68 | meta := &pb.ConvertRequest{ 69 | Value: &pb.ConvertRequest_Meta{Meta: &pb.Meta{Id: id, Type: "png", Quality: "90"}}, 70 | } 71 | stream.Send(meta) 72 | 73 | buf := make([]byte, bufSize) 74 | for { 75 | n, err := src.Read(buf) 76 | if err == io.EOF { 77 | break 78 | } 79 | if err != nil { 80 | return err 81 | } 82 | 83 | data := &pb.ConvertRequest{ 84 | Value: &pb.ConvertRequest_Chunk{Chunk: &pb.Chunk{Data: buf, Position: int64(n)}}, 85 | } 86 | err = stream.Send(data) 87 | if err != nil { 88 | return err 89 | } 90 | } 91 | 92 | err := stream.CloseSend() 93 | if err != nil { 94 | return err 95 | } 96 | 97 | return nil 98 | } 99 | 100 | func receive(stream pb.Converter_ConvertClient, dst io.Writer) error { 101 | for { 102 | resp, err := stream.Recv() 103 | if err == io.EOF { 104 | break 105 | } 106 | if err != nil { 107 | return err 108 | } 109 | _, err = dst.Write(resp.Data) 110 | if err != nil { 111 | return err 112 | } 113 | } 114 | 115 | return nil 116 | } 117 | -------------------------------------------------------------------------------- /image-proxy/client/testimage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jun06t/grpc-sample/4d1542833a64298c22e0d985e8b803e8dedd4bca/image-proxy/client/testimage.png -------------------------------------------------------------------------------- /image-proxy/proto/converter.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package converter; 4 | 5 | service Converter { 6 | rpc Convert(stream ConvertRequest) returns (stream ConvertResponse) {} 7 | } 8 | 9 | message ConvertRequest { 10 | oneof value { 11 | Meta meta = 1; 12 | Chunk chunk = 2; 13 | } 14 | } 15 | 16 | message Meta { 17 | string id = 1; 18 | string type = 2; 19 | string quality = 3; 20 | } 21 | 22 | message Chunk { 23 | bytes data = 1; 24 | int64 position = 2; 25 | } 26 | 27 | message ConvertResponse { 28 | bytes data = 1; 29 | int64 position = 2; 30 | } 31 | -------------------------------------------------------------------------------- /image-proxy/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "log" 7 | "net" 8 | "os" 9 | "os/exec" 10 | "sync" 11 | 12 | pb "github.com/jun06t/grpc-sample/image-proxy/proto" 13 | "google.golang.org/grpc" 14 | ) 15 | 16 | const ( 17 | port = ":8080" 18 | ) 19 | 20 | func main() { 21 | lis, err := net.Listen("tcp", port) 22 | if err != nil { 23 | log.Fatal(err) 24 | } 25 | 26 | s := grpc.NewServer() 27 | pb.RegisterConverterServer(s, new(server)) 28 | err = s.Serve(lis) 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | } 33 | 34 | type server struct{} 35 | 36 | func (s *server) Convert(stream pb.Converter_ConvertServer) error { 37 | buf := pool.Get().(*bytes.Buffer) 38 | defer func() { 39 | buf.Reset() 40 | pool.Put(buf) 41 | }() 42 | 43 | m, err := receive(stream, buf) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | // NOTE: generate uuid when each call 49 | uuid := "uuid-" 50 | src := uuid + "src" 51 | defer os.Remove(src) 52 | 53 | err = writeOrg(src, buf) 54 | if err != nil { 55 | return err 56 | } 57 | 58 | dst := uuid + "dst" 59 | defer os.Remove(dst) 60 | 61 | cmd := exec.Command("cwebp", "-quiet", "-mt", "-q", m.qa, "-o", dst, src) 62 | err = cmd.Run() 63 | if err != nil { 64 | return err 65 | } 66 | 67 | file, err := os.Open(dst) 68 | if err != nil { 69 | return err 70 | } 71 | defer file.Close() 72 | err = send(stream, file) 73 | if err != nil { 74 | return err 75 | } 76 | 77 | return nil 78 | } 79 | 80 | var pool = sync.Pool{ 81 | New: func() interface{} { 82 | return bytes.NewBuffer(make([]byte, 0, 1024*64)) 83 | }, 84 | } 85 | 86 | type meta struct { 87 | qa string 88 | } 89 | 90 | func receive(stream pb.Converter_ConvertServer, w io.Writer) (meta, error) { 91 | m := meta{} 92 | for { 93 | resp, err := stream.Recv() 94 | if err == io.EOF { 95 | break 96 | } 97 | if err != nil { 98 | return m, err 99 | } 100 | 101 | if mt := resp.GetMeta(); mt != nil { 102 | m.qa = mt.Quality 103 | } 104 | if chunk := resp.GetChunk(); chunk != nil { 105 | _, err := w.Write(chunk.Data) 106 | if err != nil { 107 | return m, err 108 | } 109 | } 110 | } 111 | 112 | return m, nil 113 | } 114 | 115 | func writeOrg(name string, src io.Reader) error { 116 | file, err := os.Create(name) 117 | if err != nil { 118 | return err 119 | } 120 | defer file.Close() 121 | _, err = io.Copy(file, src) 122 | if err != nil { 123 | return err 124 | } 125 | 126 | return nil 127 | } 128 | 129 | func send(stream pb.Converter_ConvertServer, r io.Reader) error { 130 | buf := make([]byte, 1024) 131 | for { 132 | n, err := r.Read(buf) 133 | if err == io.EOF { 134 | break 135 | } 136 | if err != nil { 137 | return err 138 | } 139 | 140 | data := &pb.ConvertResponse{ 141 | Data: buf, 142 | Position: int64(n), 143 | } 144 | stream.Send(data) 145 | } 146 | 147 | return nil 148 | } 149 | -------------------------------------------------------------------------------- /keepalive/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /keepalive/README.md: -------------------------------------------------------------------------------- 1 | # Keepalive gRPC sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | GODEBUG=http2debug=2 go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | GODEBUG=http2debug=2 go run client/main.go 16 | ``` 17 | 18 | Then it returns 19 | ``` 20 | 2017/11/14 14:31:42 Reply: Hello alice 21 | ``` 22 | -------------------------------------------------------------------------------- /keepalive/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "time" 7 | 8 | "google.golang.org/grpc" 9 | "google.golang.org/grpc/keepalive" 10 | 11 | pb "github.com/jun06t/grpc-sample/keepalive/proto" 12 | ) 13 | 14 | const ( 15 | address = "localhost:8080" 16 | ) 17 | 18 | var kacp = keepalive.ClientParameters{ 19 | Time: 10 * time.Second, 20 | Timeout: 5 * time.Second, 21 | PermitWithoutStream: true, 22 | } 23 | 24 | func main() { 25 | conn, err := grpc.Dial( 26 | address, grpc.WithInsecure(), 27 | grpc.WithKeepaliveParams(kacp), 28 | ) 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | defer conn.Close() 33 | 34 | c := pb.NewGreeterClient(conn) 35 | 36 | req := &pb.HelloRequest{ 37 | Name: "alice", 38 | } 39 | resp, err := c.SayHello(context.Background(), req) 40 | if err != nil { 41 | log.Fatal(err) 42 | } 43 | log.Println("Reply: ", resp.Message) 44 | select {} // Block forever; run with GODEBUG=http2debug=2 to observe ping frames and GOAWAYs due to idleness. 45 | } 46 | -------------------------------------------------------------------------------- /keepalive/proto/helloworld.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: helloworld.proto 3 | 4 | package helloworld 5 | 6 | import ( 7 | context "context" 8 | fmt "fmt" 9 | proto "github.com/golang/protobuf/proto" 10 | grpc "google.golang.org/grpc" 11 | codes "google.golang.org/grpc/codes" 12 | status "google.golang.org/grpc/status" 13 | math "math" 14 | ) 15 | 16 | // Reference imports to suppress errors if they are not otherwise used. 17 | var _ = proto.Marshal 18 | var _ = fmt.Errorf 19 | var _ = math.Inf 20 | 21 | // This is a compile-time assertion to ensure that this generated file 22 | // is compatible with the proto package it is being compiled against. 23 | // A compilation error at this line likely means your copy of the 24 | // proto package needs to be updated. 25 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 26 | 27 | type HelloRequest struct { 28 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 29 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 30 | XXX_unrecognized []byte `json:"-"` 31 | XXX_sizecache int32 `json:"-"` 32 | } 33 | 34 | func (m *HelloRequest) Reset() { *m = HelloRequest{} } 35 | func (m *HelloRequest) String() string { return proto.CompactTextString(m) } 36 | func (*HelloRequest) ProtoMessage() {} 37 | func (*HelloRequest) Descriptor() ([]byte, []int) { 38 | return fileDescriptor_17b8c58d586b62f2, []int{0} 39 | } 40 | 41 | func (m *HelloRequest) XXX_Unmarshal(b []byte) error { 42 | return xxx_messageInfo_HelloRequest.Unmarshal(m, b) 43 | } 44 | func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 45 | return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic) 46 | } 47 | func (m *HelloRequest) XXX_Merge(src proto.Message) { 48 | xxx_messageInfo_HelloRequest.Merge(m, src) 49 | } 50 | func (m *HelloRequest) XXX_Size() int { 51 | return xxx_messageInfo_HelloRequest.Size(m) 52 | } 53 | func (m *HelloRequest) XXX_DiscardUnknown() { 54 | xxx_messageInfo_HelloRequest.DiscardUnknown(m) 55 | } 56 | 57 | var xxx_messageInfo_HelloRequest proto.InternalMessageInfo 58 | 59 | func (m *HelloRequest) GetName() string { 60 | if m != nil { 61 | return m.Name 62 | } 63 | return "" 64 | } 65 | 66 | type HelloReply struct { 67 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` 68 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 69 | XXX_unrecognized []byte `json:"-"` 70 | XXX_sizecache int32 `json:"-"` 71 | } 72 | 73 | func (m *HelloReply) Reset() { *m = HelloReply{} } 74 | func (m *HelloReply) String() string { return proto.CompactTextString(m) } 75 | func (*HelloReply) ProtoMessage() {} 76 | func (*HelloReply) Descriptor() ([]byte, []int) { 77 | return fileDescriptor_17b8c58d586b62f2, []int{1} 78 | } 79 | 80 | func (m *HelloReply) XXX_Unmarshal(b []byte) error { 81 | return xxx_messageInfo_HelloReply.Unmarshal(m, b) 82 | } 83 | func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 84 | return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) 85 | } 86 | func (m *HelloReply) XXX_Merge(src proto.Message) { 87 | xxx_messageInfo_HelloReply.Merge(m, src) 88 | } 89 | func (m *HelloReply) XXX_Size() int { 90 | return xxx_messageInfo_HelloReply.Size(m) 91 | } 92 | func (m *HelloReply) XXX_DiscardUnknown() { 93 | xxx_messageInfo_HelloReply.DiscardUnknown(m) 94 | } 95 | 96 | var xxx_messageInfo_HelloReply proto.InternalMessageInfo 97 | 98 | func (m *HelloReply) GetMessage() string { 99 | if m != nil { 100 | return m.Message 101 | } 102 | return "" 103 | } 104 | 105 | func init() { 106 | proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") 107 | proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") 108 | } 109 | 110 | func init() { proto.RegisterFile("helloworld.proto", fileDescriptor_17b8c58d586b62f2) } 111 | 112 | var fileDescriptor_17b8c58d586b62f2 = []byte{ 113 | // 141 bytes of a gzipped FileDescriptorProto 114 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0x48, 0xcd, 0xc9, 115 | 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, 116 | 0x28, 0x29, 0x71, 0xf1, 0x78, 0x80, 0x78, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0x42, 117 | 0x5c, 0x2c, 0x79, 0x89, 0xb9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x92, 118 | 0x1a, 0x17, 0x17, 0x54, 0x4d, 0x41, 0x4e, 0xa5, 0x90, 0x04, 0x17, 0x7b, 0x6e, 0x6a, 0x71, 0x71, 119 | 0x62, 0x3a, 0x4c, 0x11, 0x8c, 0x6b, 0xe4, 0xc9, 0xc5, 0xee, 0x5e, 0x94, 0x9a, 0x5a, 0x92, 0x5a, 120 | 0x24, 0x64, 0xc7, 0xc5, 0x11, 0x9c, 0x58, 0x09, 0xd6, 0x25, 0x24, 0xa1, 0x87, 0xe4, 0x02, 0x64, 121 | 0xcb, 0xa4, 0xc4, 0xb0, 0xc8, 0x14, 0xe4, 0x54, 0x2a, 0x31, 0x24, 0xb1, 0x81, 0x5d, 0x6a, 0x0c, 122 | 0x08, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x53, 0x4e, 0xf7, 0xbd, 0x00, 0x00, 0x00, 123 | } 124 | 125 | // Reference imports to suppress errors if they are not otherwise used. 126 | var _ context.Context 127 | var _ grpc.ClientConn 128 | 129 | // This is a compile-time assertion to ensure that this generated file 130 | // is compatible with the grpc package it is being compiled against. 131 | const _ = grpc.SupportPackageIsVersion4 132 | 133 | // GreeterClient is the client API for Greeter service. 134 | // 135 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. 136 | type GreeterClient interface { 137 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 138 | } 139 | 140 | type greeterClient struct { 141 | cc *grpc.ClientConn 142 | } 143 | 144 | func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { 145 | return &greeterClient{cc} 146 | } 147 | 148 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 149 | out := new(HelloReply) 150 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 151 | if err != nil { 152 | return nil, err 153 | } 154 | return out, nil 155 | } 156 | 157 | // GreeterServer is the server API for Greeter service. 158 | type GreeterServer interface { 159 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 160 | } 161 | 162 | // UnimplementedGreeterServer can be embedded to have forward compatible implementations. 163 | type UnimplementedGreeterServer struct { 164 | } 165 | 166 | func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) { 167 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 168 | } 169 | 170 | func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { 171 | s.RegisterService(&_Greeter_serviceDesc, srv) 172 | } 173 | 174 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 175 | in := new(HelloRequest) 176 | if err := dec(in); err != nil { 177 | return nil, err 178 | } 179 | if interceptor == nil { 180 | return srv.(GreeterServer).SayHello(ctx, in) 181 | } 182 | info := &grpc.UnaryServerInfo{ 183 | Server: srv, 184 | FullMethod: "/helloworld.Greeter/SayHello", 185 | } 186 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 187 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 188 | } 189 | return interceptor(ctx, in, info, handler) 190 | } 191 | 192 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 193 | ServiceName: "helloworld.Greeter", 194 | HandlerType: (*GreeterServer)(nil), 195 | Methods: []grpc.MethodDesc{ 196 | { 197 | MethodName: "SayHello", 198 | Handler: _Greeter_SayHello_Handler, 199 | }, 200 | }, 201 | Streams: []grpc.StreamDesc{}, 202 | Metadata: "helloworld.proto", 203 | } 204 | -------------------------------------------------------------------------------- /keepalive/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | service Greeter { 6 | rpc SayHello(HelloRequest) returns (HelloReply) {} 7 | } 8 | 9 | message HelloRequest { 10 | string name = 1; 11 | } 12 | 13 | message HelloReply { 14 | string message = 1; 15 | } 16 | -------------------------------------------------------------------------------- /keepalive/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "net" 7 | "time" 8 | 9 | "google.golang.org/grpc" 10 | "google.golang.org/grpc/keepalive" 11 | 12 | pb "github.com/jun06t/grpc-sample/keepalive/proto" 13 | ) 14 | 15 | const ( 16 | port = ":8080" 17 | ) 18 | 19 | var kaep = keepalive.EnforcementPolicy{ 20 | MinTime: 10 * time.Second, 21 | PermitWithoutStream: true, 22 | } 23 | 24 | var kasp = keepalive.ServerParameters{ 25 | MaxConnectionIdle: 30 * time.Second, 26 | MaxConnectionAge: 30 * time.Second, 27 | MaxConnectionAgeGrace: 5 * time.Second, 28 | Time: 12 * time.Second, 29 | Timeout: 3 * time.Second, 30 | } 31 | 32 | type server struct{} 33 | 34 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 35 | time.Sleep(30 * time.Second) 36 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 37 | } 38 | 39 | func main() { 40 | lis, err := net.Listen("tcp", port) 41 | if err != nil { 42 | log.Fatal(err) 43 | } 44 | 45 | s := grpc.NewServer( 46 | grpc.KeepaliveEnforcementPolicy(kaep), 47 | grpc.KeepaliveParams(kasp), 48 | ) 49 | pb.RegisterGreeterServer(s, &server{}) 50 | err = s.Serve(lis) 51 | if err != nil { 52 | log.Fatal(err) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /metadata/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /metadata/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /metadata/README.md: -------------------------------------------------------------------------------- 1 | # Unary(Simple) gRPC Metadata sample 2 | 3 | ## Compile 4 | ``` 5 | make proto 6 | ``` 7 | 8 | ## Run gRPC server 9 | ``` 10 | go run server/main.go 11 | ``` 12 | 13 | ## Run gRRC Client 14 | ``` 15 | go run client/main.go 16 | ``` 17 | 18 | Then client says; 19 | ``` 20 | 2019/02/28 12:44:34 Reply: Hello alice 21 | 2019/02/28 12:44:34 Header: map[content-type:[application/grpc] timestamp:[Feb 28 12:44:34.956833000]] 22 | 2019/02/28 12:44:34 Trailer: map[timestamp:[Feb 28 12:44:34.956868000]] 23 | ``` 24 | 25 | And server says; 26 | ``` 27 | request id from metadata: 28 | 0. dwToyxFrRj969BcUDe7dc9 29 | ``` 30 | -------------------------------------------------------------------------------- /metadata/client/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jun06t/grpc-sample/metadata/client 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/jun06t/grpc-sample v0.0.0-20230404043014-02c9ee4cc316 7 | github.com/lithammer/shortuuid v3.0.0+incompatible 8 | google.golang.org/grpc v1.53.0 9 | ) 10 | -------------------------------------------------------------------------------- /metadata/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/jun06t/grpc-sample/metadata/interceptor" 8 | pb "github.com/jun06t/grpc-sample/metadata/proto" 9 | "github.com/lithammer/shortuuid" 10 | "google.golang.org/grpc" 11 | "google.golang.org/grpc/metadata" 12 | ) 13 | 14 | const ( 15 | address = "localhost:8080" 16 | ) 17 | 18 | func main() { 19 | run() 20 | runWithInterceptor() 21 | } 22 | 23 | func run() { 24 | conn, err := grpc.Dial( 25 | address, 26 | grpc.WithInsecure(), 27 | ) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | defer conn.Close() 32 | 33 | c := pb.NewGreeterClient(conn) 34 | 35 | req := &pb.HelloRequest{ 36 | Name: "alice", 37 | } 38 | ctx := setRequestID(context.Background()) 39 | // Make RPC using the context with the metadata. 40 | var header, trailer metadata.MD 41 | resp, err := c.SayHello(ctx, req, grpc.Header(&header), grpc.Trailer(&trailer)) 42 | if err != nil { 43 | log.Fatal(err) 44 | } 45 | log.Println("Reply: ", resp.Message) 46 | log.Printf("Header: %+v\n", header) 47 | log.Printf("Trailer: %+v\n", trailer) 48 | } 49 | 50 | func runWithInterceptor() { 51 | conn, err := grpc.Dial( 52 | address, 53 | grpc.WithInsecure(), 54 | grpc.WithUnaryInterceptor(interceptor.ClientInterceptor()), 55 | ) 56 | if err != nil { 57 | log.Fatal(err) 58 | } 59 | defer conn.Close() 60 | 61 | c := pb.NewGreeterClient(conn) 62 | 63 | req := &pb.HelloRequest{ 64 | Name: "alice", 65 | } 66 | resp, err := c.SayHello(context.Background(), req) 67 | if err != nil { 68 | log.Fatal(err) 69 | } 70 | log.Println("Reply: ", resp.Message) 71 | } 72 | 73 | func setRequestID(ctx context.Context) context.Context { 74 | id := shortuuid.New() 75 | return metadata.AppendToOutgoingContext(ctx, "x-request-id", id) 76 | } 77 | -------------------------------------------------------------------------------- /metadata/interceptor/client.go: -------------------------------------------------------------------------------- 1 | package interceptor 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/lithammer/shortuuid" 8 | "google.golang.org/grpc" 9 | "google.golang.org/grpc/metadata" 10 | ) 11 | 12 | func ClientInterceptor() grpc.UnaryClientInterceptor { 13 | return func( 14 | ctx context.Context, 15 | method string, 16 | req interface{}, 17 | reply interface{}, 18 | cc *grpc.ClientConn, 19 | invoker grpc.UnaryInvoker, 20 | opts ...grpc.CallOption, 21 | ) error { 22 | md := metadata.Pairs("x-request-id", shortuuid.New()) 23 | ctx = metadata.NewOutgoingContext(ctx, md) 24 | 25 | var header, trailer metadata.MD 26 | opts = append(opts, grpc.Header(&header)) 27 | opts = append(opts, grpc.Trailer(&trailer)) 28 | err := invoker(ctx, method, req, reply, cc, opts...) 29 | log.Printf("reply: %+v\n", reply) 30 | log.Printf("header: %+v\n", header) 31 | log.Printf("trailer: %+v\n", trailer) 32 | return err 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /metadata/interceptor/server.go: -------------------------------------------------------------------------------- 1 | package interceptor 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | "google.golang.org/grpc" 9 | "google.golang.org/grpc/codes" 10 | "google.golang.org/grpc/metadata" 11 | "google.golang.org/grpc/status" 12 | ) 13 | 14 | func ServerInterceptor( 15 | ctx context.Context, 16 | req interface{}, 17 | info *grpc.UnaryServerInfo, 18 | handler grpc.UnaryHandler, 19 | ) (interface{}, error) { 20 | defer func() { 21 | trailer := metadata.Pairs("timestamp", time.Now().Format(time.StampNano)) 22 | grpc.SetTrailer(ctx, trailer) 23 | }() 24 | 25 | header := metadata.Pairs("timestamp", time.Now().Format(time.StampNano)) 26 | grpc.SetHeader(ctx, header) 27 | 28 | err := extractRequestID(ctx) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | // call handler 34 | resp, err := handler(ctx, req) 35 | 36 | return resp, err 37 | } 38 | 39 | func extractRequestID(ctx context.Context) error { 40 | md, ok := metadata.FromIncomingContext(ctx) 41 | if !ok { 42 | return status.Errorf(codes.DataLoss, "UnarySayHello: failed to get metadata") 43 | } 44 | if t, ok := md["x-request-id"]; ok { 45 | fmt.Printf("request id from metadata:\n") 46 | for i, e := range t { 47 | fmt.Printf(" %d. %s\n", i, e) 48 | } 49 | } 50 | return nil 51 | } 52 | -------------------------------------------------------------------------------- /metadata/proto/helloworld.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: helloworld.proto 3 | 4 | package helloworld 5 | 6 | import ( 7 | context "context" 8 | fmt "fmt" 9 | proto "github.com/golang/protobuf/proto" 10 | grpc "google.golang.org/grpc" 11 | codes "google.golang.org/grpc/codes" 12 | status "google.golang.org/grpc/status" 13 | math "math" 14 | ) 15 | 16 | // Reference imports to suppress errors if they are not otherwise used. 17 | var _ = proto.Marshal 18 | var _ = fmt.Errorf 19 | var _ = math.Inf 20 | 21 | // This is a compile-time assertion to ensure that this generated file 22 | // is compatible with the proto package it is being compiled against. 23 | // A compilation error at this line likely means your copy of the 24 | // proto package needs to be updated. 25 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 26 | 27 | type HelloRequest struct { 28 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 29 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 30 | XXX_unrecognized []byte `json:"-"` 31 | XXX_sizecache int32 `json:"-"` 32 | } 33 | 34 | func (m *HelloRequest) Reset() { *m = HelloRequest{} } 35 | func (m *HelloRequest) String() string { return proto.CompactTextString(m) } 36 | func (*HelloRequest) ProtoMessage() {} 37 | func (*HelloRequest) Descriptor() ([]byte, []int) { 38 | return fileDescriptor_17b8c58d586b62f2, []int{0} 39 | } 40 | 41 | func (m *HelloRequest) XXX_Unmarshal(b []byte) error { 42 | return xxx_messageInfo_HelloRequest.Unmarshal(m, b) 43 | } 44 | func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 45 | return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic) 46 | } 47 | func (m *HelloRequest) XXX_Merge(src proto.Message) { 48 | xxx_messageInfo_HelloRequest.Merge(m, src) 49 | } 50 | func (m *HelloRequest) XXX_Size() int { 51 | return xxx_messageInfo_HelloRequest.Size(m) 52 | } 53 | func (m *HelloRequest) XXX_DiscardUnknown() { 54 | xxx_messageInfo_HelloRequest.DiscardUnknown(m) 55 | } 56 | 57 | var xxx_messageInfo_HelloRequest proto.InternalMessageInfo 58 | 59 | func (m *HelloRequest) GetName() string { 60 | if m != nil { 61 | return m.Name 62 | } 63 | return "" 64 | } 65 | 66 | type HelloReply struct { 67 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` 68 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 69 | XXX_unrecognized []byte `json:"-"` 70 | XXX_sizecache int32 `json:"-"` 71 | } 72 | 73 | func (m *HelloReply) Reset() { *m = HelloReply{} } 74 | func (m *HelloReply) String() string { return proto.CompactTextString(m) } 75 | func (*HelloReply) ProtoMessage() {} 76 | func (*HelloReply) Descriptor() ([]byte, []int) { 77 | return fileDescriptor_17b8c58d586b62f2, []int{1} 78 | } 79 | 80 | func (m *HelloReply) XXX_Unmarshal(b []byte) error { 81 | return xxx_messageInfo_HelloReply.Unmarshal(m, b) 82 | } 83 | func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 84 | return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) 85 | } 86 | func (m *HelloReply) XXX_Merge(src proto.Message) { 87 | xxx_messageInfo_HelloReply.Merge(m, src) 88 | } 89 | func (m *HelloReply) XXX_Size() int { 90 | return xxx_messageInfo_HelloReply.Size(m) 91 | } 92 | func (m *HelloReply) XXX_DiscardUnknown() { 93 | xxx_messageInfo_HelloReply.DiscardUnknown(m) 94 | } 95 | 96 | var xxx_messageInfo_HelloReply proto.InternalMessageInfo 97 | 98 | func (m *HelloReply) GetMessage() string { 99 | if m != nil { 100 | return m.Message 101 | } 102 | return "" 103 | } 104 | 105 | func init() { 106 | proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") 107 | proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") 108 | } 109 | 110 | func init() { proto.RegisterFile("helloworld.proto", fileDescriptor_17b8c58d586b62f2) } 111 | 112 | var fileDescriptor_17b8c58d586b62f2 = []byte{ 113 | // 141 bytes of a gzipped FileDescriptorProto 114 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0x48, 0xcd, 0xc9, 115 | 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, 116 | 0x28, 0x29, 0x71, 0xf1, 0x78, 0x80, 0x78, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0x42, 117 | 0x5c, 0x2c, 0x79, 0x89, 0xb9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x92, 118 | 0x1a, 0x17, 0x17, 0x54, 0x4d, 0x41, 0x4e, 0xa5, 0x90, 0x04, 0x17, 0x7b, 0x6e, 0x6a, 0x71, 0x71, 119 | 0x62, 0x3a, 0x4c, 0x11, 0x8c, 0x6b, 0xe4, 0xc9, 0xc5, 0xee, 0x5e, 0x94, 0x9a, 0x5a, 0x92, 0x5a, 120 | 0x24, 0x64, 0xc7, 0xc5, 0x11, 0x9c, 0x58, 0x09, 0xd6, 0x25, 0x24, 0xa1, 0x87, 0xe4, 0x02, 0x64, 121 | 0xcb, 0xa4, 0xc4, 0xb0, 0xc8, 0x14, 0xe4, 0x54, 0x2a, 0x31, 0x24, 0xb1, 0x81, 0x5d, 0x6a, 0x0c, 122 | 0x08, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x53, 0x4e, 0xf7, 0xbd, 0x00, 0x00, 0x00, 123 | } 124 | 125 | // Reference imports to suppress errors if they are not otherwise used. 126 | var _ context.Context 127 | var _ grpc.ClientConn 128 | 129 | // This is a compile-time assertion to ensure that this generated file 130 | // is compatible with the grpc package it is being compiled against. 131 | const _ = grpc.SupportPackageIsVersion4 132 | 133 | // GreeterClient is the client API for Greeter service. 134 | // 135 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. 136 | type GreeterClient interface { 137 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 138 | } 139 | 140 | type greeterClient struct { 141 | cc *grpc.ClientConn 142 | } 143 | 144 | func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { 145 | return &greeterClient{cc} 146 | } 147 | 148 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 149 | out := new(HelloReply) 150 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 151 | if err != nil { 152 | return nil, err 153 | } 154 | return out, nil 155 | } 156 | 157 | // GreeterServer is the server API for Greeter service. 158 | type GreeterServer interface { 159 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 160 | } 161 | 162 | // UnimplementedGreeterServer can be embedded to have forward compatible implementations. 163 | type UnimplementedGreeterServer struct { 164 | } 165 | 166 | func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) { 167 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 168 | } 169 | 170 | func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { 171 | s.RegisterService(&_Greeter_serviceDesc, srv) 172 | } 173 | 174 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 175 | in := new(HelloRequest) 176 | if err := dec(in); err != nil { 177 | return nil, err 178 | } 179 | if interceptor == nil { 180 | return srv.(GreeterServer).SayHello(ctx, in) 181 | } 182 | info := &grpc.UnaryServerInfo{ 183 | Server: srv, 184 | FullMethod: "/helloworld.Greeter/SayHello", 185 | } 186 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 187 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 188 | } 189 | return interceptor(ctx, in, info, handler) 190 | } 191 | 192 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 193 | ServiceName: "helloworld.Greeter", 194 | HandlerType: (*GreeterServer)(nil), 195 | Methods: []grpc.MethodDesc{ 196 | { 197 | MethodName: "SayHello", 198 | Handler: _Greeter_SayHello_Handler, 199 | }, 200 | }, 201 | Streams: []grpc.StreamDesc{}, 202 | Metadata: "helloworld.proto", 203 | } 204 | -------------------------------------------------------------------------------- /metadata/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | service Greeter { 6 | rpc SayHello(HelloRequest) returns (HelloReply) {} 7 | } 8 | 9 | message HelloRequest { 10 | string name = 1; 11 | } 12 | 13 | message HelloReply { 14 | string message = 1; 15 | } 16 | -------------------------------------------------------------------------------- /metadata/server/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jun06t/grpc-sample/metadata/server 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/jun06t/grpc-sample v0.0.0-20230404043014-02c9ee4cc316 7 | google.golang.org/grpc v1.53.0 8 | ) 9 | -------------------------------------------------------------------------------- /metadata/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net" 8 | "time" 9 | 10 | "github.com/jun06t/grpc-sample/metadata/interceptor" 11 | pb "github.com/jun06t/grpc-sample/metadata/proto" 12 | "google.golang.org/grpc" 13 | "google.golang.org/grpc/codes" 14 | "google.golang.org/grpc/metadata" 15 | "google.golang.org/grpc/status" 16 | ) 17 | 18 | const ( 19 | port = ":8080" 20 | ) 21 | 22 | func main() { 23 | //run() 24 | runWithInterceptor() 25 | } 26 | 27 | type server struct{} 28 | 29 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 30 | defer func() { 31 | trailer := metadata.Pairs("timestamp", time.Now().Format(time.StampNano)) 32 | grpc.SetTrailer(ctx, trailer) 33 | }() 34 | header := metadata.Pairs("timestamp", time.Now().Format(time.StampNano)) 35 | grpc.SetHeader(ctx, header) 36 | 37 | // Read metadata from client. 38 | md, ok := metadata.FromIncomingContext(ctx) 39 | if !ok { 40 | return nil, status.Errorf(codes.DataLoss, "UnarySayHello: failed to get metadata") 41 | } 42 | if t, ok := md["x-request-id"]; ok { 43 | fmt.Printf("request id from metadata:\n") 44 | for i, e := range t { 45 | fmt.Printf(" %d. %s\n", i, e) 46 | } 47 | } 48 | 49 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 50 | } 51 | 52 | type serverWithInterceptor struct{} 53 | 54 | func (s *serverWithInterceptor) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 55 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 56 | } 57 | 58 | func run() { 59 | lis, err := net.Listen("tcp", port) 60 | if err != nil { 61 | log.Fatal(err) 62 | } 63 | 64 | s := grpc.NewServer() 65 | pb.RegisterGreeterServer(s, &server{}) 66 | err = s.Serve(lis) 67 | if err != nil { 68 | log.Fatal(err) 69 | } 70 | } 71 | 72 | func runWithInterceptor() { 73 | lis, err := net.Listen("tcp", port) 74 | if err != nil { 75 | log.Fatal(err) 76 | } 77 | 78 | s := grpc.NewServer( 79 | grpc.UnaryInterceptor(interceptor.ServerInterceptor), 80 | ) 81 | pb.RegisterGreeterServer(s, &serverWithInterceptor{}) 82 | err = s.Serve(lis) 83 | if err != nil { 84 | log.Fatal(err) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /multiple-interceptors/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /multiple-interceptors/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto proto_format 2 | 3 | proto: proto_format 4 | protoc \ 5 | -I=./proto \ 6 | --go_out=plugins=grpc:./proto \ 7 | ./proto/*.proto 8 | 9 | proto_format: 10 | find ./proto/ -name "*.proto" | xargs clang-format -i 11 | 12 | -------------------------------------------------------------------------------- /multiple-interceptors/README.md: -------------------------------------------------------------------------------- 1 | # Multiple Interceptors sample 2 | 3 | ## Run gRPC server 4 | ``` 5 | go run server/main.go 6 | ``` 7 | 8 | ## Run gRRC Client 9 | ``` 10 | go run client/main.go 11 | ``` 12 | 13 | Then client says; 14 | ``` 15 | client-inter1- before invoker 16 | client-inter2- before invoker 17 | client-inter3- before invoker 18 | client-inter3- after invoker 19 | client-inter2- after invoker 20 | client-inter1- after invoker 21 | 2019/07/11 19:44:59 Reply: Hello alice 22 | ``` 23 | 24 | And server says; 25 | ``` 26 | server-inter1- before handler 27 | server-inter2- before handler 28 | server-inter3- before handler 29 | handler 30 | server-inter3- after handler 31 | server-inter2- after handler 32 | server-inter1- after handler 33 | ``` -------------------------------------------------------------------------------- /multiple-interceptors/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" 8 | "google.golang.org/grpc" 9 | 10 | "github.com/jun06t/grpc-sample/multiple-interceptors/interceptor" 11 | pb "github.com/jun06t/grpc-sample/multiple-interceptors/proto" 12 | ) 13 | 14 | const ( 15 | address = "localhost:8080" 16 | ) 17 | 18 | func main() { 19 | //run() 20 | runWithMiddleware() 21 | } 22 | 23 | func run() { 24 | conn, err := grpc.Dial( 25 | address, 26 | grpc.WithInsecure(), 27 | grpc.WithUnaryInterceptor(interceptor.ClientInterceptor("client-inter1-")), 28 | grpc.WithUnaryInterceptor(interceptor.ClientInterceptor("client-inter2-")), 29 | grpc.WithUnaryInterceptor(interceptor.ClientInterceptor("client-inter3-")), 30 | ) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | defer conn.Close() 35 | 36 | c := pb.NewGreeterClient(conn) 37 | 38 | req := &pb.HelloRequest{ 39 | Name: "alice", 40 | } 41 | resp, err := c.SayHello(context.Background(), req) 42 | if err != nil { 43 | log.Fatal(err) 44 | } 45 | log.Println("Reply: ", resp.Message) 46 | } 47 | 48 | func runWithMiddleware() { 49 | conn, err := grpc.Dial( 50 | address, 51 | grpc.WithInsecure(), 52 | grpc.WithUnaryInterceptor( 53 | grpc_middleware.ChainUnaryClient( 54 | interceptor.ClientInterceptor("client-inter1-"), 55 | interceptor.ClientInterceptor("client-inter2-"), 56 | interceptor.ClientInterceptor("client-inter3-"), 57 | ), 58 | ), 59 | ) 60 | if err != nil { 61 | log.Fatal(err) 62 | } 63 | defer conn.Close() 64 | 65 | c := pb.NewGreeterClient(conn) 66 | 67 | req := &pb.HelloRequest{ 68 | Name: "alice", 69 | } 70 | resp, err := c.SayHello(context.Background(), req) 71 | if err != nil { 72 | log.Fatal(err) 73 | } 74 | log.Println("Reply: ", resp.Message) 75 | } 76 | -------------------------------------------------------------------------------- /multiple-interceptors/interceptor/client.go: -------------------------------------------------------------------------------- 1 | package interceptor 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "google.golang.org/grpc" 8 | ) 9 | 10 | func ClientInterceptor(prefix string) grpc.UnaryClientInterceptor { 11 | return func( 12 | ctx context.Context, 13 | method string, 14 | req interface{}, 15 | reply interface{}, 16 | cc *grpc.ClientConn, 17 | invoker grpc.UnaryInvoker, 18 | opts ...grpc.CallOption, 19 | ) error { 20 | fmt.Println(prefix, "before invoker") 21 | err := invoker(ctx, method, req, reply, cc, opts...) 22 | fmt.Println(prefix, "after invoker") 23 | return err 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /multiple-interceptors/interceptor/server.go: -------------------------------------------------------------------------------- 1 | package interceptor 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "google.golang.org/grpc" 8 | ) 9 | 10 | func ServerInterceptor(prefix string) grpc.UnaryServerInterceptor { 11 | return func(ctx context.Context, 12 | req interface{}, 13 | info *grpc.UnaryServerInfo, 14 | handler grpc.UnaryHandler, 15 | ) (interface{}, error) { 16 | fmt.Println(prefix, "before handler") 17 | // call handler 18 | resp, err := handler(ctx, req) 19 | fmt.Println(prefix, "after handler") 20 | 21 | return resp, err 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /multiple-interceptors/proto/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | service Greeter { 6 | rpc SayHello(HelloRequest) returns (HelloReply) {} 7 | } 8 | 9 | message HelloRequest { 10 | string name = 1; 11 | } 12 | 13 | message HelloReply { 14 | string message = 1; 15 | } 16 | -------------------------------------------------------------------------------- /multiple-interceptors/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net" 8 | 9 | grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" 10 | "google.golang.org/grpc" 11 | 12 | "github.com/jun06t/grpc-sample/multiple-interceptors/interceptor" 13 | pb "github.com/jun06t/grpc-sample/multiple-interceptors/proto" 14 | ) 15 | 16 | const ( 17 | port = ":8080" 18 | ) 19 | 20 | func main() { 21 | //run() 22 | runWithMiddleware() 23 | } 24 | 25 | type server struct{} 26 | 27 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 28 | fmt.Println("handler") 29 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 30 | } 31 | 32 | func run() { 33 | lis, err := net.Listen("tcp", port) 34 | if err != nil { 35 | log.Fatal(err) 36 | } 37 | 38 | s := grpc.NewServer( 39 | grpc.UnaryInterceptor(interceptor.ServerInterceptor("server-inter1-")), 40 | grpc.UnaryInterceptor(interceptor.ServerInterceptor("server-inter2-")), 41 | grpc.UnaryInterceptor(interceptor.ServerInterceptor("server-inter3-")), 42 | ) 43 | pb.RegisterGreeterServer(s, &server{}) 44 | err = s.Serve(lis) 45 | if err != nil { 46 | log.Fatal(err) 47 | } 48 | } 49 | 50 | func runWithMiddleware() { 51 | lis, err := net.Listen("tcp", port) 52 | if err != nil { 53 | log.Fatal(err) 54 | } 55 | 56 | s := grpc.NewServer( 57 | grpc_middleware.WithUnaryServerChain( 58 | interceptor.ServerInterceptor("server-inter1-"), 59 | interceptor.ServerInterceptor("server-inter2-"), 60 | interceptor.ServerInterceptor("server-inter3-"), 61 | ), 62 | ) 63 | pb.RegisterGreeterServer(s, &server{}) 64 | err = s.Serve(lis) 65 | if err != nil { 66 | log.Fatal(err) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /openapi/buf.gen.yaml: -------------------------------------------------------------------------------- 1 | version: v1 2 | plugins: 3 | - plugin: buf.build/grpc-ecosystem/openapiv2:v2.15.2 4 | out: ../../docs/chat 5 | opt: 6 | - allow_merge=true 7 | - disable_default_errors=true 8 | - logtostderr=true 9 | - omit_enum_default_value=true 10 | - json_names_for_fields=false 11 | - visibility_restriction_selectors=HTTP 12 | - output_format=yaml -------------------------------------------------------------------------------- /openapi/buf.lock: -------------------------------------------------------------------------------- 1 | # Generated by buf. DO NOT EDIT. 2 | version: v2 3 | deps: 4 | - name: buf.build/googleapis/googleapis 5 | commit: 2bbd25900cb34c79bae97d85c948d3cf 6 | digest: b5:3a12d858b0efcf53739b0fe6b4f83ccef246a0a26d257dc50a7d0d0794be3b6df941cf7e1dbf92f81c25ae60806132bf37b1af76a9311be8905f5da52c6a5f66 7 | -------------------------------------------------------------------------------- /openapi/buf.yaml: -------------------------------------------------------------------------------- 1 | version: v2 2 | modules: 3 | - path: proto 4 | lint: 5 | use: 6 | - DEFAULT 7 | breaking: 8 | use: 9 | - FILE 10 | deps: 11 | - buf.build/googleapis/googleapis 12 | 13 | -------------------------------------------------------------------------------- /openapi/proto/alive.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | import "google/api/annotations.proto"; 4 | 5 | package jun06t.grpc_sample.openapi; 6 | 7 | service AliveService { 8 | rpc GetStatus(Empty) returns (AliveResponse) { 9 | option (google.api.http) = { 10 | get: "/alive" 11 | }; 12 | } 13 | }; 14 | 15 | message Empty {} 16 | 17 | message AliveResponse { 18 | bool status = 1; 19 | } 20 | -------------------------------------------------------------------------------- /openapi/proto/user.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | import "google/api/annotations.proto"; 4 | import "alive.proto"; 5 | 6 | package jun06t.grpc_sample.openapi; 7 | 8 | service UserService { 9 | rpc GetUser(GetUserRequest) returns (UserResponse) { 10 | option (google.api.http) = { 11 | get: "/user/{id}" 12 | }; 13 | } 14 | 15 | rpc GetUsersByGroup(UserGroupRequest) returns (UsersResponse) { 16 | option (google.api.http) = { 17 | get: "/user" 18 | }; 19 | } 20 | 21 | rpc UpdateUser(UpdateUserRequest) returns (Empty) { 22 | option (google.api.http) = { 23 | put: "/user/{id}" 24 | body: "*" 25 | }; 26 | } 27 | } 28 | 29 | message GetUserRequest { 30 | string id = 1; 31 | } 32 | 33 | message UpdateUserRequest { 34 | string id = 1; 35 | string name = 2; 36 | int32 age = 3; 37 | } 38 | 39 | message UserResponse { 40 | string id = 1; 41 | string name = 2; 42 | int32 age = 3; 43 | } 44 | 45 | enum Group { 46 | USER = 0; 47 | ADMIN = 1; 48 | DEVELOPER = 2; 49 | } 50 | 51 | message UserGroupRequest { 52 | Group group = 1; 53 | } 54 | 55 | message UsersResponse { 56 | Group group = 1; 57 | repeated UserResponse users = 2; 58 | } 59 | -------------------------------------------------------------------------------- /protoc/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /protoc/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: proto_basic proto_patah proto_plugin proto_format 2 | 3 | proto_basic: 4 | protoc \ 5 | -I=./basic \ 6 | --go_out=./basic \ 7 | ./basic/*.proto 8 | 9 | proto_path: 10 | protoc \ 11 | -I=./path \ 12 | --go_out=./path \ 13 | ./path/*.proto 14 | 15 | proto_plugin: 16 | protoc \ 17 | -I=./plugin \ 18 | --go_out=plugins=grpc:./plugin \ 19 | ./plugin/*.proto 20 | 21 | proto_format: 22 | find ./basic/ -name "*.proto" | xargs clang-format -i 23 | find ./path/ -name "*.proto" | xargs clang-format -i 24 | find ./grpc/ -name "*.proto" | xargs clang-format -i 25 | 26 | -------------------------------------------------------------------------------- /protoc/basic/person.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: person.proto 3 | 4 | package basic 5 | 6 | import ( 7 | fmt "fmt" 8 | proto "github.com/golang/protobuf/proto" 9 | math "math" 10 | ) 11 | 12 | // Reference imports to suppress errors if they are not otherwise used. 13 | var _ = proto.Marshal 14 | var _ = fmt.Errorf 15 | var _ = math.Inf 16 | 17 | // This is a compile-time assertion to ensure that this generated file 18 | // is compatible with the proto package it is being compiled against. 19 | // A compilation error at this line likely means your copy of the 20 | // proto package needs to be updated. 21 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 22 | 23 | type Person struct { 24 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 25 | Id int32 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` 26 | Email string `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"` 27 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 28 | XXX_unrecognized []byte `json:"-"` 29 | XXX_sizecache int32 `json:"-"` 30 | } 31 | 32 | func (m *Person) Reset() { *m = Person{} } 33 | func (m *Person) String() string { return proto.CompactTextString(m) } 34 | func (*Person) ProtoMessage() {} 35 | func (*Person) Descriptor() ([]byte, []int) { 36 | return fileDescriptor_4c9e10cf24b1156d, []int{0} 37 | } 38 | 39 | func (m *Person) XXX_Unmarshal(b []byte) error { 40 | return xxx_messageInfo_Person.Unmarshal(m, b) 41 | } 42 | func (m *Person) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 43 | return xxx_messageInfo_Person.Marshal(b, m, deterministic) 44 | } 45 | func (m *Person) XXX_Merge(src proto.Message) { 46 | xxx_messageInfo_Person.Merge(m, src) 47 | } 48 | func (m *Person) XXX_Size() int { 49 | return xxx_messageInfo_Person.Size(m) 50 | } 51 | func (m *Person) XXX_DiscardUnknown() { 52 | xxx_messageInfo_Person.DiscardUnknown(m) 53 | } 54 | 55 | var xxx_messageInfo_Person proto.InternalMessageInfo 56 | 57 | func (m *Person) GetName() string { 58 | if m != nil { 59 | return m.Name 60 | } 61 | return "" 62 | } 63 | 64 | func (m *Person) GetId() int32 { 65 | if m != nil { 66 | return m.Id 67 | } 68 | return 0 69 | } 70 | 71 | func (m *Person) GetEmail() string { 72 | if m != nil { 73 | return m.Email 74 | } 75 | return "" 76 | } 77 | 78 | func init() { 79 | proto.RegisterType((*Person)(nil), "basic.Person") 80 | } 81 | 82 | func init() { proto.RegisterFile("person.proto", fileDescriptor_4c9e10cf24b1156d) } 83 | 84 | var fileDescriptor_4c9e10cf24b1156d = []byte{ 85 | // 105 bytes of a gzipped FileDescriptorProto 86 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0x48, 0x2d, 0x2a, 87 | 0xce, 0xcf, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x4d, 0x4a, 0x2c, 0xce, 0x4c, 0x56, 88 | 0x72, 0xe2, 0x62, 0x0b, 0x00, 0x0b, 0x0b, 0x09, 0x71, 0xb1, 0xe4, 0x25, 0xe6, 0xa6, 0x4a, 0x30, 89 | 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x81, 0xd9, 0x42, 0x7c, 0x5c, 0x4c, 0x99, 0x29, 0x12, 0x4c, 0x0a, 90 | 0x8c, 0x1a, 0xac, 0x41, 0x4c, 0x99, 0x29, 0x42, 0x22, 0x5c, 0xac, 0xa9, 0xb9, 0x89, 0x99, 0x39, 91 | 0x12, 0xcc, 0x60, 0x45, 0x10, 0x4e, 0x12, 0x1b, 0xd8, 0x44, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 92 | 0xff, 0xd4, 0xa8, 0x65, 0x38, 0x61, 0x00, 0x00, 0x00, 93 | } 94 | -------------------------------------------------------------------------------- /protoc/basic/person.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package basic; 3 | 4 | message Person { 5 | string name = 1; 6 | int32 id = 2; 7 | string email = 3; 8 | } 9 | -------------------------------------------------------------------------------- /protoc/path/device.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: device.proto 3 | 4 | package path 5 | 6 | import ( 7 | fmt "fmt" 8 | proto "github.com/golang/protobuf/proto" 9 | math "math" 10 | ) 11 | 12 | // Reference imports to suppress errors if they are not otherwise used. 13 | var _ = proto.Marshal 14 | var _ = fmt.Errorf 15 | var _ = math.Inf 16 | 17 | // This is a compile-time assertion to ensure that this generated file 18 | // is compatible with the proto package it is being compiled against. 19 | // A compilation error at this line likely means your copy of the 20 | // proto package needs to be updated. 21 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 22 | 23 | type Device struct { 24 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` 25 | Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` 26 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 27 | XXX_unrecognized []byte `json:"-"` 28 | XXX_sizecache int32 `json:"-"` 29 | } 30 | 31 | func (m *Device) Reset() { *m = Device{} } 32 | func (m *Device) String() string { return proto.CompactTextString(m) } 33 | func (*Device) ProtoMessage() {} 34 | func (*Device) Descriptor() ([]byte, []int) { 35 | return fileDescriptor_870276a56ac00da5, []int{0} 36 | } 37 | 38 | func (m *Device) XXX_Unmarshal(b []byte) error { 39 | return xxx_messageInfo_Device.Unmarshal(m, b) 40 | } 41 | func (m *Device) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 42 | return xxx_messageInfo_Device.Marshal(b, m, deterministic) 43 | } 44 | func (m *Device) XXX_Merge(src proto.Message) { 45 | xxx_messageInfo_Device.Merge(m, src) 46 | } 47 | func (m *Device) XXX_Size() int { 48 | return xxx_messageInfo_Device.Size(m) 49 | } 50 | func (m *Device) XXX_DiscardUnknown() { 51 | xxx_messageInfo_Device.DiscardUnknown(m) 52 | } 53 | 54 | var xxx_messageInfo_Device proto.InternalMessageInfo 55 | 56 | func (m *Device) GetId() string { 57 | if m != nil { 58 | return m.Id 59 | } 60 | return "" 61 | } 62 | 63 | func (m *Device) GetName() string { 64 | if m != nil { 65 | return m.Name 66 | } 67 | return "" 68 | } 69 | 70 | func init() { 71 | proto.RegisterType((*Device)(nil), "path.Device") 72 | } 73 | 74 | func init() { proto.RegisterFile("device.proto", fileDescriptor_870276a56ac00da5) } 75 | 76 | var fileDescriptor_870276a56ac00da5 = []byte{ 77 | // 86 bytes of a gzipped FileDescriptorProto 78 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0x49, 0x2d, 0xcb, 79 | 0x4c, 0x4e, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x29, 0x48, 0x2c, 0xc9, 0x50, 0xd2, 80 | 0xe1, 0x62, 0x73, 0x01, 0x8b, 0x0a, 0xf1, 0x71, 0x31, 0x65, 0xa6, 0x48, 0x30, 0x2a, 0x30, 0x6a, 81 | 0x70, 0x06, 0x31, 0x65, 0xa6, 0x08, 0x09, 0x71, 0xb1, 0xe4, 0x25, 0xe6, 0xa6, 0x4a, 0x30, 0x81, 82 | 0x45, 0xc0, 0xec, 0x24, 0x36, 0xb0, 0x56, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb1, 0xc6, 83 | 0xc7, 0x50, 0x4a, 0x00, 0x00, 0x00, 84 | } 85 | -------------------------------------------------------------------------------- /protoc/path/device.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package path; 3 | 4 | message Device { 5 | string id = 1; 6 | string name = 2; 7 | } 8 | -------------------------------------------------------------------------------- /protoc/path/path.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: path 3 | 4 | package path 5 | 6 | import ( 7 | fmt "fmt" 8 | proto "github.com/golang/protobuf/proto" 9 | math "math" 10 | ) 11 | 12 | // Reference imports to suppress errors if they are not otherwise used. 13 | var _ = proto.Marshal 14 | var _ = fmt.Errorf 15 | var _ = math.Inf 16 | 17 | // This is a compile-time assertion to ensure that this generated file 18 | // is compatible with the proto package it is being compiled against. 19 | // A compilation error at this line likely means your copy of the 20 | // proto package needs to be updated. 21 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 22 | 23 | func init() { proto.RegisterFile("path", fileDescriptor_a0af9f865bf637e6) } 24 | 25 | var fileDescriptor_a0af9f865bf637e6 = []byte{ 26 | // 30 bytes of a gzipped FileDescriptorProto 27 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x62, 0x29, 0x48, 0x2c, 0xc9, 28 | 0x00, 0x04, 0x00, 0x00, 0xff, 0xff, 0x16, 0x70, 0xc9, 0xcf, 0x06, 0x00, 0x00, 0x00, 29 | } 30 | -------------------------------------------------------------------------------- /protoc/path/person.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: person.proto 3 | 4 | package path 5 | 6 | import ( 7 | fmt "fmt" 8 | proto "github.com/golang/protobuf/proto" 9 | math "math" 10 | ) 11 | 12 | // Reference imports to suppress errors if they are not otherwise used. 13 | var _ = proto.Marshal 14 | var _ = fmt.Errorf 15 | var _ = math.Inf 16 | 17 | // This is a compile-time assertion to ensure that this generated file 18 | // is compatible with the proto package it is being compiled against. 19 | // A compilation error at this line likely means your copy of the 20 | // proto package needs to be updated. 21 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 22 | 23 | type Person struct { 24 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 25 | Id int32 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` 26 | Email string `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"` 27 | Device *Device `protobuf:"bytes,4,opt,name=device,proto3" json:"device,omitempty"` 28 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 29 | XXX_unrecognized []byte `json:"-"` 30 | XXX_sizecache int32 `json:"-"` 31 | } 32 | 33 | func (m *Person) Reset() { *m = Person{} } 34 | func (m *Person) String() string { return proto.CompactTextString(m) } 35 | func (*Person) ProtoMessage() {} 36 | func (*Person) Descriptor() ([]byte, []int) { 37 | return fileDescriptor_4c9e10cf24b1156d, []int{0} 38 | } 39 | 40 | func (m *Person) XXX_Unmarshal(b []byte) error { 41 | return xxx_messageInfo_Person.Unmarshal(m, b) 42 | } 43 | func (m *Person) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 44 | return xxx_messageInfo_Person.Marshal(b, m, deterministic) 45 | } 46 | func (m *Person) XXX_Merge(src proto.Message) { 47 | xxx_messageInfo_Person.Merge(m, src) 48 | } 49 | func (m *Person) XXX_Size() int { 50 | return xxx_messageInfo_Person.Size(m) 51 | } 52 | func (m *Person) XXX_DiscardUnknown() { 53 | xxx_messageInfo_Person.DiscardUnknown(m) 54 | } 55 | 56 | var xxx_messageInfo_Person proto.InternalMessageInfo 57 | 58 | func (m *Person) GetName() string { 59 | if m != nil { 60 | return m.Name 61 | } 62 | return "" 63 | } 64 | 65 | func (m *Person) GetId() int32 { 66 | if m != nil { 67 | return m.Id 68 | } 69 | return 0 70 | } 71 | 72 | func (m *Person) GetEmail() string { 73 | if m != nil { 74 | return m.Email 75 | } 76 | return "" 77 | } 78 | 79 | func (m *Person) GetDevice() *Device { 80 | if m != nil { 81 | return m.Device 82 | } 83 | return nil 84 | } 85 | 86 | func init() { 87 | proto.RegisterType((*Person)(nil), "path.Person") 88 | } 89 | 90 | func init() { proto.RegisterFile("person.proto", fileDescriptor_4c9e10cf24b1156d) } 91 | 92 | var fileDescriptor_4c9e10cf24b1156d = []byte{ 93 | // 138 bytes of a gzipped FileDescriptorProto 94 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0x48, 0x2d, 0x2a, 95 | 0xce, 0xcf, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x29, 0x48, 0x2c, 0xc9, 0x90, 0xe2, 96 | 0x49, 0x49, 0x2d, 0xcb, 0x4c, 0x4e, 0x85, 0x88, 0x29, 0x65, 0x70, 0xb1, 0x05, 0x80, 0xd5, 0x08, 97 | 0x09, 0x71, 0xb1, 0xe4, 0x25, 0xe6, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x81, 0xd9, 98 | 0x42, 0x7c, 0x5c, 0x4c, 0x99, 0x29, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x4c, 0x99, 0x29, 99 | 0x42, 0x22, 0x5c, 0xac, 0xa9, 0xb9, 0x89, 0x99, 0x39, 0x12, 0xcc, 0x60, 0x45, 0x10, 0x8e, 0x90, 100 | 0x0a, 0x17, 0x1b, 0xc4, 0x4c, 0x09, 0x16, 0x05, 0x46, 0x0d, 0x6e, 0x23, 0x1e, 0x3d, 0x90, 0x45, 101 | 0x7a, 0x2e, 0x60, 0xb1, 0x20, 0xa8, 0x5c, 0x12, 0x1b, 0xd8, 0x42, 0x63, 0x40, 0x00, 0x00, 0x00, 102 | 0xff, 0xff, 0x98, 0x08, 0x42, 0x2a, 0x94, 0x00, 0x00, 0x00, 103 | } 104 | -------------------------------------------------------------------------------- /protoc/path/person.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package path; 3 | 4 | import 'device.proto'; 5 | 6 | message Person { 7 | string name = 1; 8 | int32 id = 2; 9 | string email = 3; 10 | Device device = 4; 11 | } 12 | -------------------------------------------------------------------------------- /protoc/plugin/helloworld.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: helloworld.proto 3 | 4 | package helloworld 5 | 6 | import ( 7 | context "context" 8 | fmt "fmt" 9 | proto "github.com/golang/protobuf/proto" 10 | grpc "google.golang.org/grpc" 11 | codes "google.golang.org/grpc/codes" 12 | status "google.golang.org/grpc/status" 13 | math "math" 14 | ) 15 | 16 | // Reference imports to suppress errors if they are not otherwise used. 17 | var _ = proto.Marshal 18 | var _ = fmt.Errorf 19 | var _ = math.Inf 20 | 21 | // This is a compile-time assertion to ensure that this generated file 22 | // is compatible with the proto package it is being compiled against. 23 | // A compilation error at this line likely means your copy of the 24 | // proto package needs to be updated. 25 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 26 | 27 | type HelloRequest struct { 28 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 29 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 30 | XXX_unrecognized []byte `json:"-"` 31 | XXX_sizecache int32 `json:"-"` 32 | } 33 | 34 | func (m *HelloRequest) Reset() { *m = HelloRequest{} } 35 | func (m *HelloRequest) String() string { return proto.CompactTextString(m) } 36 | func (*HelloRequest) ProtoMessage() {} 37 | func (*HelloRequest) Descriptor() ([]byte, []int) { 38 | return fileDescriptor_17b8c58d586b62f2, []int{0} 39 | } 40 | 41 | func (m *HelloRequest) XXX_Unmarshal(b []byte) error { 42 | return xxx_messageInfo_HelloRequest.Unmarshal(m, b) 43 | } 44 | func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 45 | return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic) 46 | } 47 | func (m *HelloRequest) XXX_Merge(src proto.Message) { 48 | xxx_messageInfo_HelloRequest.Merge(m, src) 49 | } 50 | func (m *HelloRequest) XXX_Size() int { 51 | return xxx_messageInfo_HelloRequest.Size(m) 52 | } 53 | func (m *HelloRequest) XXX_DiscardUnknown() { 54 | xxx_messageInfo_HelloRequest.DiscardUnknown(m) 55 | } 56 | 57 | var xxx_messageInfo_HelloRequest proto.InternalMessageInfo 58 | 59 | func (m *HelloRequest) GetName() string { 60 | if m != nil { 61 | return m.Name 62 | } 63 | return "" 64 | } 65 | 66 | type HelloReply struct { 67 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` 68 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 69 | XXX_unrecognized []byte `json:"-"` 70 | XXX_sizecache int32 `json:"-"` 71 | } 72 | 73 | func (m *HelloReply) Reset() { *m = HelloReply{} } 74 | func (m *HelloReply) String() string { return proto.CompactTextString(m) } 75 | func (*HelloReply) ProtoMessage() {} 76 | func (*HelloReply) Descriptor() ([]byte, []int) { 77 | return fileDescriptor_17b8c58d586b62f2, []int{1} 78 | } 79 | 80 | func (m *HelloReply) XXX_Unmarshal(b []byte) error { 81 | return xxx_messageInfo_HelloReply.Unmarshal(m, b) 82 | } 83 | func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 84 | return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) 85 | } 86 | func (m *HelloReply) XXX_Merge(src proto.Message) { 87 | xxx_messageInfo_HelloReply.Merge(m, src) 88 | } 89 | func (m *HelloReply) XXX_Size() int { 90 | return xxx_messageInfo_HelloReply.Size(m) 91 | } 92 | func (m *HelloReply) XXX_DiscardUnknown() { 93 | xxx_messageInfo_HelloReply.DiscardUnknown(m) 94 | } 95 | 96 | var xxx_messageInfo_HelloReply proto.InternalMessageInfo 97 | 98 | func (m *HelloReply) GetMessage() string { 99 | if m != nil { 100 | return m.Message 101 | } 102 | return "" 103 | } 104 | 105 | func init() { 106 | proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") 107 | proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") 108 | } 109 | 110 | func init() { proto.RegisterFile("helloworld.proto", fileDescriptor_17b8c58d586b62f2) } 111 | 112 | var fileDescriptor_17b8c58d586b62f2 = []byte{ 113 | // 141 bytes of a gzipped FileDescriptorProto 114 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0x48, 0xcd, 0xc9, 115 | 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, 116 | 0x28, 0x29, 0x71, 0xf1, 0x78, 0x80, 0x78, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0x42, 117 | 0x5c, 0x2c, 0x79, 0x89, 0xb9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x92, 118 | 0x1a, 0x17, 0x17, 0x54, 0x4d, 0x41, 0x4e, 0xa5, 0x90, 0x04, 0x17, 0x7b, 0x6e, 0x6a, 0x71, 0x71, 119 | 0x62, 0x3a, 0x4c, 0x11, 0x8c, 0x6b, 0xe4, 0xc9, 0xc5, 0xee, 0x5e, 0x94, 0x9a, 0x5a, 0x92, 0x5a, 120 | 0x24, 0x64, 0xc7, 0xc5, 0x11, 0x9c, 0x58, 0x09, 0xd6, 0x25, 0x24, 0xa1, 0x87, 0xe4, 0x02, 0x64, 121 | 0xcb, 0xa4, 0xc4, 0xb0, 0xc8, 0x14, 0xe4, 0x54, 0x2a, 0x31, 0x24, 0xb1, 0x81, 0x5d, 0x6a, 0x0c, 122 | 0x08, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x53, 0x4e, 0xf7, 0xbd, 0x00, 0x00, 0x00, 123 | } 124 | 125 | // Reference imports to suppress errors if they are not otherwise used. 126 | var _ context.Context 127 | var _ grpc.ClientConn 128 | 129 | // This is a compile-time assertion to ensure that this generated file 130 | // is compatible with the grpc package it is being compiled against. 131 | const _ = grpc.SupportPackageIsVersion4 132 | 133 | // GreeterClient is the client API for Greeter service. 134 | // 135 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. 136 | type GreeterClient interface { 137 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 138 | } 139 | 140 | type greeterClient struct { 141 | cc *grpc.ClientConn 142 | } 143 | 144 | func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { 145 | return &greeterClient{cc} 146 | } 147 | 148 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 149 | out := new(HelloReply) 150 | err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) 151 | if err != nil { 152 | return nil, err 153 | } 154 | return out, nil 155 | } 156 | 157 | // GreeterServer is the server API for Greeter service. 158 | type GreeterServer interface { 159 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 160 | } 161 | 162 | // UnimplementedGreeterServer can be embedded to have forward compatible implementations. 163 | type UnimplementedGreeterServer struct { 164 | } 165 | 166 | func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) { 167 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 168 | } 169 | 170 | func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { 171 | s.RegisterService(&_Greeter_serviceDesc, srv) 172 | } 173 | 174 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 175 | in := new(HelloRequest) 176 | if err := dec(in); err != nil { 177 | return nil, err 178 | } 179 | if interceptor == nil { 180 | return srv.(GreeterServer).SayHello(ctx, in) 181 | } 182 | info := &grpc.UnaryServerInfo{ 183 | Server: srv, 184 | FullMethod: "/helloworld.Greeter/SayHello", 185 | } 186 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 187 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 188 | } 189 | return interceptor(ctx, in, info, handler) 190 | } 191 | 192 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 193 | ServiceName: "helloworld.Greeter", 194 | HandlerType: (*GreeterServer)(nil), 195 | Methods: []grpc.MethodDesc{ 196 | { 197 | MethodName: "SayHello", 198 | Handler: _Greeter_SayHello_Handler, 199 | }, 200 | }, 201 | Streams: []grpc.StreamDesc{}, 202 | Metadata: "helloworld.proto", 203 | } 204 | -------------------------------------------------------------------------------- /protoc/plugin/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | service Greeter { 6 | rpc SayHello(HelloRequest) returns (HelloReply) {} 7 | } 8 | 9 | message HelloRequest { 10 | string name = 1; 11 | } 12 | 13 | message HelloReply { 14 | string message = 1; 15 | } 16 | -------------------------------------------------------------------------------- /protoeasy/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Proto 3 | BasedOnStyle: Google 4 | AlignConsecutiveAssignments: true 5 | AlignConsecutiveDeclarations: true 6 | -------------------------------------------------------------------------------- /protoeasy/README.md: -------------------------------------------------------------------------------- 1 | # protoeasy-sample 2 | 3 | ## Install 4 | Install protoeasy. 5 | ``` 6 | go get -u go.pedge.io/protoeasy/cmd/protoeasy 7 | ``` 8 | 9 | And also other libraries. 10 | ``` 11 | cat <