Skip to content

Latest commit

 

History

History
149 lines (134 loc) · 3.75 KB

write_client.md

File metadata and controls

149 lines (134 loc) · 3.75 KB

Write Client Code

Implement Main Method

Build Connection

  • Basic version
    conn, err := grpc.Dial(address)
  • With dial option(s)
    opts := []grpc.DialOption{
        opt1, opt2, opt3
    }
    conn, err := grpc.Dial(address, opts...)

Available Dial Option

  • Security
    • No security
      grpc.WithInsecure()
  • Interceptor
    • Unary interceptor
      grpc.WithUnaryInterceptor(unaryInterceptorFunc)
    • Stream interceptor
      grpc.WithStreamInterceptor(streamInterceptorFunc)

Build Client

  • Basic version
    client := pb.NewAbcClient(conn)      // Abc is the service name

Build Context

  • With timeout
    ctx, cancel := context.WithTimeout(context.Background(), time.Second * 5)
  • With deadline
    deadline := time.Now().Add(time.Duration(5 * time.Second))
    ctx, cancel := context.WithDeadline(context.Background(), deadline)
  • With metadata
    import "google.golang.org/grpc/metadata"
    ctx := metadata.NewOutgoingContext(context.Background(), md)

Create Metadata (Optional)

  • Option 1
    md := metadata.New(map[string]string{"key1": "val1", "key2": "val2"})
  • Option 2
    md := metadata.Pairs(
      "key1", "val1",
      "key2", "val2"
    )

Add Metadata to Context (Optional)

  • Create a new context by metadata
    ctx := metadata.NewOutgoingContext(context.Background(), md)
  • Append metadata to an existing context
    ctx2 := metadata.AppendToOutgoingContext(ctx1, "key1", "val1", "key2", "val2")

Call Remote Method

  • Unary
    output, err = client.someRemoteFunc(ctx, &input)
  • Server-side streaming
    outputStream, streamErr := client.someRemoteFunc(ctx, input)
    
    for {                                            // Process multiple outputs
        output, err := outputStream.Recv()
        if err == io.EOF {                           // End of stream, break infinite loop
            log.Print("EOF")
            break
        }
    
        if err == nil {
            // Process single output.
        }
    }
  • Client-side streaming
    inputStream, err := client.someRemoteFunc(ctx)   // Create input stream
    
    for _ , input := range inputs {                  // Send multiple inputs
        if err := inputStream.Send(&input); err != nil {
            log.Fatalf("%v.Send(%v) = %v", inputStream, input, err)
        }
    }
    
    output, err := inputStream.CloseAndRecv()        // Close sending and get output

Handle Response Error

import "google.golang.org/grpc/status"

output, err = client.someRemoteFunc(ctx, &input)
if err != nil {
    errorCode    := status.Code(err)
    errorStatus  := status.Convert(err)
    errorDetails := errorStatus.Details()
    
    // Error handling
}

Read Metadata from Response

  • Unary
    var header, trailer metadata.MD
    output, err = client.someRemoteFunc(ctx, &input, grpc.Header(&header), grpc.Trailer(&trailer))
    // Process header and trailer map
  • Streaming
    outputStream, streamErr := client.someRemoteFunc(ctx, input)
    header, err := outputStream.Header()
    trailer     := outputStream.Trailer()
    // Process header and trailer map