- Basic version
conn, err := grpc.Dial(address)
- With dial option(s)
opts := []grpc.DialOption{ opt1, opt2, opt3 } conn, err := grpc.Dial(address, opts...)
- Security
- No security
grpc.WithInsecure()
- No security
- Interceptor
- Unary interceptor
grpc.WithUnaryInterceptor(unaryInterceptorFunc)
- Stream interceptor
grpc.WithStreamInterceptor(streamInterceptorFunc)
- Unary interceptor
- Basic version
client := pb.NewAbcClient(conn) // Abc is the service name
- 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)
- Option 1
md := metadata.New(map[string]string{"key1": "val1", "key2": "val2"})
- Option 2
md := metadata.Pairs( "key1", "val1", "key2", "val2" )
- 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")
- 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
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
}
- 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