12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
package mainimport (//"context""flag""log""golang.org/x/net/context"pb "github.com/smallnest/grpc/a/pb""google.golang.org/grpc")var (address = flag.String("addr", "localhost:8972", "address")name = flag.String("n", "world", "name"))func main() {flag.Parse()// 串連伺服器conn, err := grpc.Dial(*address, grpc.WithInsecure(), grpc.WithUnaryInterceptor(UnaryClientInterceptor),grpc.WithStreamInterceptor(StreamClientInterceptor))if err != nil {log.Fatalf("faild to connect: %v", err)}defer conn.Close()c := pb.NewGreeterClient(conn)r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: *name})if err != nil {log.Fatalf("could not greet: %v", err)}log.Printf("Greeting: %s", r.Message)}func UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {log.Printf("before invoker. method: %+v, request:%+v", method, req)err := invoker(ctx, method, req, reply, cc, opts...)log.Printf("after invoker. reply: %+v", reply)return err}func StreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {log.Printf("before invoker. method: %+v, StreamDesc:%+v", method, desc)clientStream, err := streamer(ctx, desc, cc, method, opts...)log.Printf("before invoker. method: %+v", method)return clientStream, err} |