|
| 1 | +/* |
| 2 | + * |
| 3 | + * Copyright 2018 gRPC authors. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + * |
| 17 | + */ |
| 18 | + |
| 19 | +// Binary client is an example client. |
| 20 | +package main |
| 21 | + |
| 22 | +import ( |
| 23 | + "context" |
| 24 | + "flag" |
| 25 | + "fmt" |
| 26 | + "io" |
| 27 | + "log" |
| 28 | + "time" |
| 29 | + |
| 30 | + "golang.org/x/oauth2" |
| 31 | + "google.golang.org/grpc" |
| 32 | + "google.golang.org/grpc/credentials" |
| 33 | + "google.golang.org/grpc/credentials/oauth" |
| 34 | + ecpb "google.golang.org/grpc/examples/features/proto/echo" |
| 35 | + "google.golang.org/grpc/testdata" |
| 36 | +) |
| 37 | + |
| 38 | +var addr = flag.String("addr", "localhost:50051", "the address to connect to") |
| 39 | + |
| 40 | +const fallbackToken = "some-secret-token" |
| 41 | + |
| 42 | +// logger is to mock a sophisticated logging system. To simplify the example, we just print out the content. |
| 43 | +func logger(format string, a ...interface{}) { |
| 44 | + fmt.Printf("LOG:\t"+format+"\n", a...) |
| 45 | +} |
| 46 | + |
| 47 | +// unaryInterceptor is an example unary interceptor. |
| 48 | +func unaryInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { |
| 49 | + var credsConfigured bool |
| 50 | + for _, o := range opts { |
| 51 | + _, ok := o.(grpc.PerRPCCredsCallOption) |
| 52 | + if ok { |
| 53 | + credsConfigured = true |
| 54 | + break |
| 55 | + } |
| 56 | + } |
| 57 | + if !credsConfigured { |
| 58 | + opts = append(opts, grpc.PerRPCCredentials(oauth.NewOauthAccess(&oauth2.Token{ |
| 59 | + AccessToken: fallbackToken, |
| 60 | + }))) |
| 61 | + } |
| 62 | + start := time.Now() |
| 63 | + err := invoker(ctx, method, req, reply, cc, opts...) |
| 64 | + end := time.Now() |
| 65 | + logger("RPC: %s, start time: %s, end time: %s, err: %v", method, start.Format("Basic"), end.Format(time.RFC3339), err) |
| 66 | + return err |
| 67 | +} |
| 68 | + |
| 69 | +// wrappedStream wraps around the embedded grpc.ClientStream, and intercepts the RecvMsg and |
| 70 | +// SendMsg method call. |
| 71 | +type wrappedStream struct { |
| 72 | + grpc.ClientStream |
| 73 | +} |
| 74 | + |
| 75 | +func (w *wrappedStream) RecvMsg(m interface{}) error { |
| 76 | + logger("Receive a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339)) |
| 77 | + return w.ClientStream.RecvMsg(m) |
| 78 | +} |
| 79 | + |
| 80 | +func (w *wrappedStream) SendMsg(m interface{}) error { |
| 81 | + logger("Send a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339)) |
| 82 | + return w.ClientStream.SendMsg(m) |
| 83 | +} |
| 84 | + |
| 85 | +func newWrappedStream(s grpc.ClientStream) grpc.ClientStream { |
| 86 | + return &wrappedStream{s} |
| 87 | +} |
| 88 | + |
| 89 | +// streamInterceptor is an example stream interceptor. |
| 90 | +func streamInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { |
| 91 | + var credsConfigured bool |
| 92 | + for _, o := range opts { |
| 93 | + _, ok := o.(*grpc.PerRPCCredsCallOption) |
| 94 | + if ok { |
| 95 | + credsConfigured = true |
| 96 | + } |
| 97 | + } |
| 98 | + if !credsConfigured { |
| 99 | + opts = append(opts, grpc.PerRPCCredentials(oauth.NewOauthAccess(&oauth2.Token{ |
| 100 | + AccessToken: fallbackToken, |
| 101 | + }))) |
| 102 | + } |
| 103 | + s, err := streamer(ctx, desc, cc, method, opts...) |
| 104 | + if err != nil { |
| 105 | + return nil, err |
| 106 | + } |
| 107 | + return newWrappedStream(s), nil |
| 108 | +} |
| 109 | + |
| 110 | +func callUnaryEcho(client ecpb.EchoClient, message string) { |
| 111 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 112 | + defer cancel() |
| 113 | + resp, err := client.UnaryEcho(ctx, &ecpb.EchoRequest{Message: message}) |
| 114 | + if err != nil { |
| 115 | + log.Fatalf("client.UnaryEcho(_) = _, %v: ", err) |
| 116 | + } |
| 117 | + fmt.Println("UnaryEcho: ", resp.Message) |
| 118 | +} |
| 119 | + |
| 120 | +func callBidiStreamingEcho(client ecpb.EchoClient) { |
| 121 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 122 | + defer cancel() |
| 123 | + c, err := client.BidirectionalStreamingEcho(ctx) |
| 124 | + if err != nil { |
| 125 | + return |
| 126 | + } |
| 127 | + for i := 0; i < 5; i++ { |
| 128 | + if err := c.Send(&ecpb.EchoRequest{Message: fmt.Sprintf("Request %d", i+1)}); err != nil { |
| 129 | + log.Fatalf("failed to send request due to error: %v", err) |
| 130 | + } |
| 131 | + } |
| 132 | + c.CloseSend() |
| 133 | + for { |
| 134 | + resp, err := c.Recv() |
| 135 | + if err == io.EOF { |
| 136 | + break |
| 137 | + } |
| 138 | + if err != nil { |
| 139 | + log.Fatalf("failed to receive response due to error: %v", err) |
| 140 | + } |
| 141 | + fmt.Println("BidiStreaming Echo: ", resp.Message) |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +func main() { |
| 146 | + flag.Parse() |
| 147 | + |
| 148 | + // Create tls based credential. |
| 149 | + creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") |
| 150 | + if err != nil { |
| 151 | + log.Fatalf("failed to load credentials: %v", err) |
| 152 | + } |
| 153 | + |
| 154 | + // Set up a connection to the server. |
| 155 | + conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(creds), grpc.WithUnaryInterceptor(unaryInterceptor), grpc.WithStreamInterceptor(streamInterceptor)) |
| 156 | + if err != nil { |
| 157 | + log.Fatalf("did not connect: %v", err) |
| 158 | + } |
| 159 | + defer conn.Close() |
| 160 | + |
| 161 | + // Make a echo client and send RPCs. |
| 162 | + rgc := ecpb.NewEchoClient(conn) |
| 163 | + callUnaryEcho(rgc, "hello world") |
| 164 | + callBidiStreamingEcho(rgc) |
| 165 | +} |
0 commit comments