### Get gRPC Hello World Example Code Source: https://github.com/grpc/grpc-go/blob/master/examples/helloworld/README.md Use 'go get' to download the client and server code for the greeter example. Ensure your Go environment is set up correctly. ```console go get google.golang.org/grpc/examples/helloworld/greeter_client go get google.golang.org/grpc/examples/helloworld/greeter_server ``` -------------------------------- ### Navigate to Route Guide Example Directory Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Change your current directory to the route_guide example within the gRPC Go project. This is necessary before running any example-specific commands. ```shell $ cd $GOPATH/src/google.golang.org/grpc/examples/route_guide ``` -------------------------------- ### Start gRPC Server for Reflection Testing Source: https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md Run the example server with reflection enabled. Ensure you are in the grpc-go directory. ```sh cd /examples go run features/reflection/server/main.go ``` -------------------------------- ### Run gRPC Go Route Guide Client Source: https://github.com/grpc/grpc-go/blob/master/examples/route_guide/README.md Compile and run the route guide client. Assumes you are in the root of the route_guide folder. ```sh $ go run client/client.go ``` -------------------------------- ### Run gRPC Server for RPC Errors Example Source: https://github.com/grpc/grpc-go/blob/master/Documentation/rpc-errors.md Command to start the server for the RPC errors example. ```bash $ go run examples/rpc_errors/server/main.go ``` -------------------------------- ### Run gRPC Go Route Guide Server Source: https://github.com/grpc/grpc-go/blob/master/examples/route_guide/README.md Compile and run the route guide server. Assumes you are in the root of the route_guide folder. ```sh $ go run server/server.go ``` -------------------------------- ### Start gRPC Server in Go Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Initializes and starts a gRPC server. This involves setting up a listener, creating a new gRPC server instance, registering the service implementation, and serving requests. ```go flag.Parse() lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port)) if err != nil { log.Fatalf("failed to listen: %v", err) } grpcServer := grpc.NewServer() pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{}) ... grpcServer.Serve(lis) ``` -------------------------------- ### Enable TLS for gRPC Go Route Guide Client Source: https://github.com/grpc/grpc-go/blob/master/examples/route_guide/README.md Run the route guide client with TLS enabled using the -tls=true flag. ```sh $ go run client/client.go -tls=true ``` -------------------------------- ### Run gRPC Client for RPC Errors Example Source: https://github.com/grpc/grpc-go/blob/master/Documentation/rpc-errors.md Command to run the client for the RPC errors example. ```bash $ go run examples/rpc_errors/client/main.go ``` -------------------------------- ### Enable TLS for gRPC Go Route Guide Server Source: https://github.com/grpc/grpc-go/blob/master/examples/route_guide/README.md Run the route guide server with TLS enabled using the -tls=true flag. ```sh $ go run server/server.go -tls=true ``` -------------------------------- ### Run gRPC Client Source: https://github.com/grpc/grpc-go/blob/master/examples/features/authentication/README.md Command to start the gRPC client for testing authentication. ```bash go run client/main.go ``` -------------------------------- ### Run the Wait For Ready Example Source: https://github.com/grpc/grpc-go/blob/master/examples/features/wait_for_ready/README.md Execute the Go program to observe the 'wait for ready' behavior in gRPC calls. ```bash go run main.go ``` -------------------------------- ### Run gRPC Client Source: https://github.com/grpc/grpc-go/blob/master/examples/features/flow_control/README.md Starts the gRPC client. This should be run after the server. ```bash go run ./client ``` -------------------------------- ### Run gRPC Hello World Server Source: https://github.com/grpc/grpc-go/blob/master/examples/helloworld/README.md Execute the greeter_server binary in the background using its path derived from GOPATH. This starts the gRPC server. ```console $(go env GOPATH)/bin/greeter_server & ``` -------------------------------- ### Run gRPC Server Source: https://github.com/grpc/grpc-go/blob/master/examples/features/authentication/README.md Command to start the gRPC server for testing authentication. ```bash go run server/main.go ``` -------------------------------- ### Run gRPC Server Source: https://github.com/grpc/grpc-go/blob/master/examples/features/flow_control/README.md Starts the gRPC server. Ensure this is run before the client. ```bash go run ./server ``` -------------------------------- ### Install gRPC xDS Resolver and Balancers Source: https://github.com/grpc/grpc-go/blob/master/examples/features/xds/README.md Import this package to install the xDS resolvers and balancers for gRPC. Ensure the GRPC_XDS_BOOTSTRAP environment variable is set. ```go _ "google.golang.org/grpc/xds" // To install the xds resolvers and balancers. ``` -------------------------------- ### Install gRPC-Go Source: https://github.com/grpc/grpc-go/blob/master/README.md Add this import to your Go code to automatically fetch gRPC-Go dependencies during build, run, or test. ```go import "google.golang.org/grpc" ``` -------------------------------- ### Client Output Example Source: https://github.com/grpc/grpc-go/blob/master/examples/features/flow_control/README.md Expected output from the gRPC client demonstrating flow control blocking and stream completion. ```log 2023/09/19 15:49:49 New stream began. 2023/09/19 15:49:50 Sending is blocked. 2023/09/19 15:49:51 Sent 25 messages. 2023/09/19 15:49:53 Read 25 messages. 2023/09/19 15:49:53 Stream ended successfully. ``` -------------------------------- ### Server Output Example Source: https://github.com/grpc/grpc-go/blob/master/examples/features/flow_control/README.md Expected output from the gRPC server demonstrating flow control blocking and stream completion. ```log 2023/09/19 15:49:49 New stream began. 2023/09/19 15:49:51 Read 25 messages. 2023/09/19 15:49:52 Sending is blocked. 2023/09/19 15:49:53 Sent 25 messages. 2023/09/19 15:49:53 Stream ended successfully. ``` -------------------------------- ### Pick First Load Balancer Output Source: https://github.com/grpc/grpc-go/blob/master/examples/features/load_balancing/README.md Example output when using the 'pick_first' load balancing policy. All RPCs are directed to the first successfully connected backend. ```text this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) ``` -------------------------------- ### Download gRPC Go Package Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Use 'go get' to download the gRPC Go package. Ensure you have the Go environment set up. ```shell $ go get google.golang.org/grpc ``` -------------------------------- ### Register Compressor Implementation Source: https://github.com/grpc/grpc-go/blob/master/Documentation/compression.md Implement a compression algorithm by registering it using `encoding.RegisterCompressor`. See `grpc/encoding/gzip/gzip.go` for an example. -------------------------------- ### Client-Side Compression Call Options Source: https://github.com/grpc/grpc-go/blob/master/Documentation/compression.md Configure client-side compression using `UseCompressor` for specific RPCs or `WithDefaultCallOptions` to set defaults for a `ClientConn`. If the compressor is not installed, an `Internal` error occurs. ```go func UseCompressor(name) CallOption {} ``` -------------------------------- ### Enable TLS on gRPC Server Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-auth-support.md Configure TLS for a gRPC server by loading server certificates and keys using `credentials.NewServerTLSFromFile`. Then, create a listener and start the gRPC server with the generated credentials. ```go creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) if err != nil { log.Fatalf("Failed to generate credentials %v", err) } lis, err := net.Listen("tcp", ":0") server := grpc.NewServer(grpc.Creds(creds)) ... server.Serve(lis) ``` -------------------------------- ### Run Health Check Servers Source: https://github.com/grpc/grpc-go/blob/master/examples/features/health/README.md Starts gRPC servers with specified ports and sleep durations for health check demonstrations. ```bash go run server/main.go -port=50051 -sleep=5s ``` ```bash go run server/main.go -port=50052 -sleep=10s ``` -------------------------------- ### gRPC Server Response Example Source: https://github.com/grpc/grpc-go/blob/master/examples/features/customloadbalancer/README.md This output shows the responses received from the gRPC servers. The addresses in the response indicate which server handled the request, demonstrating the load balancing. ```text this is examples/customloadbalancing (from localhost:50050) this is examples/customloadbalancing (from localhost:50050) this is examples/customloadbalancing (from localhost:50051) this is examples/customloadbalancing (from localhost:50050) this is examples/customloadbalancing (from localhost:50050) this is examples/customloadbalancing (from localhost:50051) this is examples/customloadbalancing (from localhost:50050) this is examples/customloadbalancing (from localhost:50050) this is examples/customloadbalancing (from localhost:50051) ``` -------------------------------- ### Run gRPC Server Source: https://github.com/grpc/grpc-go/blob/master/examples/features/error_handling/README.md Start the gRPC server. It is configured to return an error if the 'Name' field in the RPC request is empty. Ensure this is run before the client. ```sh go run ./server/main.go ``` -------------------------------- ### Install Stream Interceptor on gRPC Server Source: https://github.com/grpc/grpc-go/blob/master/examples/features/interceptor/README.md Configure a gRPC server to use a stream interceptor by providing the StreamInterceptor ServerOption to NewServer. ```go grpc.NewServer(grpc.StreamInterceptor(yourStreamInterceptor)) ``` -------------------------------- ### Generate gRPC Go Client and Server Code Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Use 'protoc' with Go plugins to generate gRPC client and server interfaces from a .proto file. Ensure protoc and the gRPC-Go plugin are installed. ```shell protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative "route_guide.proto" ``` -------------------------------- ### Round Robin Load Balancer Output Source: https://github.com/grpc/grpc-go/blob/master/examples/features/load_balancing/README.md Example output when using the 'round_robin' load balancing policy. RPCs are distributed sequentially across available backends. ```text this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50052) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50052) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50052) this is examples/load_balancing (from :50051) this is examples/load_balancing (from :50052) this is examples/load_balancing (from :50051) ``` -------------------------------- ### Client-side Unary Interceptor Source: https://github.com/grpc/grpc-go/blob/master/examples/features/interceptor/README.md Details on implementing and installing unary interceptors for client-side RPCs. ```APIDOC ## Client-side Unary Interceptor ### Description Client-side unary interceptors allow observation and control of unary RPC calls before they are invoked and after they complete. ### Method `google.golang.org/grpc.UnaryClientInterceptor` ### Signature ```golang func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error ``` ### Implementation Details Interceptors typically involve three parts: pre-processing (examining call arguments like context, method, request, and options), invoking the RPC using the provided `invoker`, and post-processing (handling the reply and error). ### Installation Configure the `ClientConn` using `grpc.Dial` with the `grpc.WithUnaryInterceptor` DialOption. ```go conn, err := grpc.Dial(address, grpc.WithUnaryInterceptor(myUnaryInterceptor)) ``` ``` -------------------------------- ### Implement RPC Retries with Backoff Strategy Source: https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md When retrying failed RPCs, implement a backoff strategy to avoid overwhelming the server. This example retries `codes.Unavailable` errors with an increasing delay. ```go var res *MyResponse var err error retryableStatusCodes := map[codes.Code]bool{ codes.Unavailable: true, // etc } // Retry the RPC a maximum number of times. for i := 0; i < maxRetries; i++ { // Make the RPC. res, err = client.MyRPC(context.TODO(), &MyRequest{}) // Check if the RPC was successful. if !retryableStatusCodes[status.Code(err)] { // The RPC was successful or errored in a non-retryable way; // do not retry. break } // The RPC is retryable; wait for a backoff period before retrying. backoff := time.Duration(i+1) * time.Second log.Printf("Error calling MyRPC: %v; retrying in %v", err, backoff) time.Sleep(backoff) } // Check if the RPC was successful after all retries. if err != nil { // All retries failed, so handle the error appropriately log.Printf("Error calling MyRPC: %v", err) return nil, err } // Use the response as appropriate. log.Printf("MyRPC response: %v", res) ``` -------------------------------- ### Start gRPC Server with Filewatcher Policy Source: https://github.com/grpc/grpc-go/blob/master/examples/features/authz/README.md Run the gRPC server with the filewatcher option enabled to dynamically load RBAC policies from a file. Set the log severity to 'info' to observe policy reload activities. ```bash GRPC_GO_LOG_SEVERITY_LEVEL=info go run server/main.go --authz-option filewatcher ``` -------------------------------- ### Configure Go Modules for China Access Source: https://github.com/grpc/grpc-go/blob/master/README.md Use the 'replace' feature in go.mod to alias golang.org packages when accessing them from China. This example replaces the main gRPC package. ```sh go mod edit -replace=google.golang.org/grpc=github.com/grpc/grpc-go@latest go mod tidy go mod vendor go build -mod=vendor ``` -------------------------------- ### Run gRPC Hello World Client Source: https://github.com/grpc/grpc-go/blob/master/examples/helloworld/README.md Execute the greeter_client binary to send a request to the running server and display the received greeting. The output 'Greeting: Hello world' confirms successful communication. ```console $(go env GOPATH)/bin/greeter_client Greeting: Hello world ``` -------------------------------- ### Build gRPC Client and Server Binaries Source: https://github.com/grpc/grpc-go/blob/master/internal/xds/test/e2e/README.md Use these commands to compile the Go client and server binaries for interop testing. Ensure the paths to the source files are correct. ```sh go build -o ./binaries/client ../../../../interop/xds/client/ ``` ```sh go build -o ./binaries/server ../../../../interop/xds/server/ ``` -------------------------------- ### Server-side Unary Interceptor Source: https://github.com/grpc/grpc-go/blob/master/examples/features/interceptor/README.md Details on implementing and installing unary interceptors for server-side RPCs. ```APIDOC ## Server-side Unary Interceptor ### Description Server-side unary interceptors allow observation and control of incoming unary RPC requests before they are handled by the service implementation. ### Method `google.golang.org/grpc.UnaryServerInterceptor` ### Signature ```golang func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) ``` ### Implementation Details Similar to client-side unary interceptors, these interceptors can perform actions before calling the `handler` and after receiving the response or error. ### Installation Configure the gRPC server using `grpc.NewServer` with the `grpc.UnaryInterceptor` ServerOption. ```go server := grpc.NewServer(grpc.UnaryInterceptor(myUnaryServerInterceptor)) ``` ``` -------------------------------- ### Client-side Stream Interceptor Source: https://github.com/grpc/grpc-go/blob/master/examples/features/interceptor/README.md Details on implementing and installing stream interceptors for client-side RPCs. ```APIDOC ## Client-side Stream Interceptor ### Description Client-side stream interceptors enable interception of streaming RPC operations, allowing for observation and modification of message sending and receiving. ### Method `google.golang.org/grpc.StreamClientInterceptor` ### Signature ```golang func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) ``` ### Implementation Details Stream interceptors involve pre-processing and then wrapping the `ClientStream` returned by the `streamer`. The wrapped stream overrides methods like `SendMsg` and `RecvMsg` to inject custom logic. ### Installation Configure the `ClientConn` using `grpc.Dial` with the `grpc.WithStreamInterceptor` DialOption. ```go conn, err := grpc.Dial(address, grpc.WithStreamInterceptor(myStreamInterceptor)) ``` ``` -------------------------------- ### Server-Side Stream Interceptor Source: https://github.com/grpc/grpc-go/blob/master/examples/features/interceptor/README.md Defines the type for server-side stream interceptors and provides an example of its signature. ```APIDOC ## Server-Side Stream Interceptor ### Description The type for server-side stream interceptors is `StreamServerInterceptor`. It is a function type with the specified signature. ### Signature ```golang func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error ``` ### Installation To install a stream interceptor on a Server, configure `NewServer` with the `StreamInterceptor` `ServerOption`. ``` -------------------------------- ### Register a Custom Compressor Source: https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md Implement a Compressor and register it using an init function. This is typically done in a separate package and imported anonymously. ```go package gzip import "google.golang.org/grpc/encoding" func init() { encoding.RegisterCompressor(compressor{}) } // ... implementation of compressor ... ``` -------------------------------- ### Run gRPC Server and Clients Source: https://github.com/grpc/grpc-go/blob/master/examples/features/advancedtls/README.md Commands to build and run the gRPC server and its associated clients. Ensure the credentials directory is correctly specified. ```bash # Run the server $ go run server/main.go -credentials_directory $(pwd)/creds # Run the clients from the `grpc-go/examples/features/advancedtls` directory $ go run client/main.go -credentials_directory $(pwd)/creds ``` -------------------------------- ### Import Compressor Package Source: https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md Import the desired compressor package to register it globally. This is necessary for both client and server to recognize and use the compressor. ```go package myclient import _ "google.golang.org/grpc/encoding/gzip" ``` -------------------------------- ### Create TLS Server Credentials Source: https://github.com/grpc/grpc-go/blob/master/examples/features/encryption/README.md Configure TLS for the server using certificate and key files. This is used to establish a secure server-authenticated connection. ```go credentials.NewServerTLSFromFile("server_cert.pem", "server_key.pem") ``` -------------------------------- ### Generate TLS Credentials Source: https://github.com/grpc/grpc-go/blob/master/examples/features/advancedtls/README.md Command to regenerate the TLS credentials, certificates, and CRLs used in the advancedtls examples. This script should be run from the specified directory. ```bash ./generate.sh ``` -------------------------------- ### Register a Custom Codec Source: https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md Implement a Codec and register it using an init function. This is typically done in a separate package and imported anonymously. ```go package proto import "google.golang.org/grpc/encoding" func init() { encoding.RegisterCodec(protoCodec{}) } // ... implementation of protoCodec ... ``` -------------------------------- ### RouteGuide Server Struct and Methods Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Defines the routeGuideServer struct and its methods for handling gRPC requests. This includes placeholders for actual implementation logic. ```go type routeGuideServer struct { ... } ... func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { ... } ... func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { ... } ... func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { ... } ... func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { ... } ... ``` -------------------------------- ### Build gRPC Server Docker Image Source: https://github.com/grpc/grpc-go/blob/master/examples/features/csm_observability/README.md Build a Docker image for the gRPC server from the grpc-go directory. Replace with your desired image tag. ```bash docker build -t -f examples/features/csm_observability/server/Dockerfile . ``` -------------------------------- ### Get Base64 Modulus from Public Key (Go) Source: https://github.com/grpc/grpc-go/blob/master/testdata/spiffe_end2end/README.md Extracts the base64-encoded modulus from an RSA public key. This is useful for SPIFFE Bundle Map JSON files. ```go func GetBase64ModulusFromPublicKey(key *rsa.PublicKey) string { return base64.RawURLEncoding.EncodeToString(key.N.Bytes()) } block, _ := pem.Decode(rawPemCert) cert, _ := x509.ParseCertificate(block.Bytes) publicKey := cert.PublicKey.(*rsa.PublicKey) fmt.Println(GetBase64ModulusFromPublicKey(publicKey)) ``` -------------------------------- ### Create TLS Client Credentials Source: https://github.com/grpc/grpc-go/blob/master/examples/features/encryption/README.md Configure TLS for the client using a CA certificate file. This is used to verify the server's certificate and establish a secure connection. ```go credentials.NewClientTLSFromFile("ca_cert.pem", "x.test.example.com") ``` -------------------------------- ### Build gRPC Client Docker Image Source: https://github.com/grpc/grpc-go/blob/master/examples/features/csm_observability/README.md Build a Docker image for the gRPC client from the grpc-go directory. Replace with your desired image tag. ```bash docker build -t -f examples/features/csm_observability/client/Dockerfile . ``` -------------------------------- ### Define Protocol Buffer Message Type Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Define message types for request and response payloads using Protocol Buffers. This example shows the 'Point' message with latitude and longitude. ```proto // Points are represented as latitude-longitude pairs in the E7 representation // (degrees multiplied by 10**7 and rounded to the nearest integer). // Latitudes should be in the range +/- 90 degrees and longitude should be in // the range +/- 180 degrees (inclusive). message Point { int32 latitude = 1; int32 longitude = 2; } ``` -------------------------------- ### Create gRPC Channel Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Establishes a connection to a gRPC server. Use `grpc.NewClient` with the server address. Ensure to close the connection when done using `defer conn.Close()`. ```go conn, err := grpc.NewClient(*serverAddr) if err != nil { ... } defer conn.Close() ``` -------------------------------- ### Run gRPC Interop Tests with Specific Client Path Source: https://github.com/grpc/grpc-go/blob/master/internal/xds/test/e2e/README.md Run the Go test suite, specifying the path to the client binary using the `-client` flag. This is useful when testing against clients built with other languages. ```sh go test . -v -client=$HOME/grpc-java/interop-testing/build/install/grpc-interop-testing/bin/xds-test-client ``` -------------------------------- ### Run Streaming Benchmark with Compression Source: https://github.com/grpc/grpc-go/blob/master/Documentation/benchmark.md Simulate a server workload with streaming RPCs, large messages, and gzip compression enabled. Use this to test performance under specific high-load conditions. ```bash $ go run google.golang.org/grpc/benchmark/benchmain/main.go \ -workloads=streaming \ -reqSizeBytes=1024 \ -respSizeBytes=1024 \ -compression=gzip ``` -------------------------------- ### Import Another Codec Package Source: https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md To use a codec other than the default 'proto', import its package anonymously. This registers the codec with the gRPC encoding package. ```go import _ "path/to/another/codec" ``` -------------------------------- ### Enable gRPC Logging Source: https://github.com/grpc/grpc-go/blob/master/examples/features/debugging/README.md Set environment variables to enable detailed logging for gRPC. Use GRPC_GO_LOG_VERBOSITY_LEVEL for verbosity and GRPC_GO_LOG_SEVERITY_LEVEL for severity. ```bash GRPC_GO_LOG_VERBOSITY_LEVEL=99 GRPC_GO_LOG_SEVERITY_LEVEL=info ``` -------------------------------- ### Run gRPC Interop Tests Source: https://github.com/grpc/grpc-go/blob/master/internal/xds/test/e2e/README.md Execute the Go test suite. The `-v` flag enables verbose output. ```sh go test . -v ``` -------------------------------- ### Send Header and Trailer in Unary Server Call (Go) Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md Set header and trailer metadata to be sent to the client in a unary RPC. Use the RPC handler's context or one derived from it. ```go func (s *server) SomeRPC(ctx context.Context, in *pb.someRequest) (*pb.someResponse, error) { // create and set header header := metadata.Pairs("header-key", "val") grpc.SetHeader(ctx, header) // create and set trailer trailer := metadata.Pairs("trailer-key", "val") grpc.SetTrailer(ctx, trailer) } ``` -------------------------------- ### Enable Server Reflection in Go gRPC Server Source: https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md Import the reflection package and register the reflection service on your gRPC server to enable server reflection. ```go import ( "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" "google.golang.org/grpc/reflection" ) const ( // ... ) func main() { // ... s := grpc.NewServer() pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHello}) // Register reflection service on gRPC server. reflection.Register(s) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } ``` -------------------------------- ### Send Header and Trailer in Streaming Server Call (Go) Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md Send header and trailer metadata to the client using the ServerStream interface for streaming RPCs. Ensure the stream object is correctly used. ```go func (s *server) SomeStreamingRPC(stream pb.Service_SomeStreamingRPCServer) error { // create and set header header := metadata.Pairs("header-key", "val") stream.SetHeader(header) // create and set trailer trailer := metadata.Pairs("trailer-key", "val") stream.SetTrailer(trailer) } ``` -------------------------------- ### Set Default Compressor for Client Source: https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md Configure a default compressor for all RPCs sent through a client by using `grpc.WithDefaultCallOptions` with `grpc.UseCompressor` when creating the client. ```go myclient := grpc.NewClient(target, grpc.WithDefaultCallOptions(grpc.UseCompressor("gzip"))) ``` -------------------------------- ### Generate Go gRPC Bindings with Disabled Server Unimplementation Check Source: https://github.com/grpc/grpc-go/blob/master/cmd/protoc-gen-go-grpc/README.md Use this command to generate Go gRPC bindings while disabling the default behavior that requires unimplemented server methods. This is useful for backward compatibility but not recommended for new projects. ```sh protoc --go-grpc_out=. --go-grpc_opt=require_unimplemented_servers=false[,other options...] ``` -------------------------------- ### Create Metadata using Pairs Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md The `metadata.Pairs` function allows creating metadata by providing key-value pairs. Values with the same key are merged into a list. Keys are automatically converted to lowercase. ```go md := metadata.Pairs( "key1", "val1", "key1", "val1-2", // "key1" will have map value []string{"val1", "val1-2"} "key2", "val2", ) ``` -------------------------------- ### List All Services Exposed by a gRPC Server Source: https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md Use grpcurl with the -plaintext flag to list all services available on the server. Replace localhost:50051 with your server's address. ```sh grpcurl -plaintext localhost:50051 list ``` -------------------------------- ### Run Local Tests for gRPC-Go Source: https://github.com/grpc/grpc-go/blob/master/CONTRIBUTING.md Execute the full test suite locally to ensure all tests pass before submitting a pull request. This includes running vet checks and standard tests. ```bash ./scripts/vet.sh ``` ```bash go test -cpu 1,4 -timeout 7m ./... ``` ```bash go test -race -cpu 1,4 -timeout 7m ./... ``` -------------------------------- ### Define gRPC Service Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Use the 'service' keyword in a .proto file to define a gRPC service. ```proto service RouteGuide { ... } ``` -------------------------------- ### List Methods of a Specific gRPC Service Source: https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md Use grpcurl with the -plaintext flag and the full service name to list all methods within that service. ```sh grpcurl -plaintext localhost:50051 list helloworld.Greeter ``` -------------------------------- ### Run gRPC Client with HTTP/2 Debugging Source: https://github.com/grpc/grpc-go/blob/master/examples/features/keepalive/README.md Execute the gRPC client application with HTTP/2 debugging enabled. ```bash GODEBUG=http2debug=2 go run client/main.go ``` -------------------------------- ### Create New Outgoing Context with Metadata Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md Use `metadata.NewOutgoingContext` to create a new context with specific metadata. This replaces any existing metadata, so use `metadata.Join` to preserve it. ```go // create a new context with some metadata md := metadata.Pairs("k1", "v1", "k1", "v2", "k2", "v3") ctx := metadata.NewOutgoingContext(context.Background(), md) // later, add some more metadata to the context (e.g. in an interceptor) send, _ := metadata.FromOutgoingContext(ctx) newMD := metadata.Pairs("k3", "v3") ctx = metadata.NewOutgoingContext(ctx, metadata.Join(send, newMD)) // make unary RPC response, err := client.SomeRPC(ctx, someRequest) // or make streaming RPC stream, err := client.SomeStreamingRPC(ctx) ``` -------------------------------- ### Generate gRPC Client Stub Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Creates a client stub for interacting with service methods after a gRPC channel is established. Use the `NewClient` function from the generated protobuf package. ```go client := pb.NewRouteGuideClient(conn) ``` -------------------------------- ### Create and Convert Status Error in Go Source: https://github.com/grpc/grpc-go/blob/master/Documentation/rpc-errors.md Demonstrates creating a status.Status error with a code and description, and converting it to a standard error type. ```go st := status.New(codes.NotFound, "some description") err := st.Err() ``` ```go err := status.Error(codes.NotFound, "some description") ``` -------------------------------- ### Describe a Specific gRPC Method Source: https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md Use grpcurl with the -plaintext flag and the full method name to inspect the method's signature, including request and response types. ```sh grpcurl -plaintext localhost:50051 describe helloworld.Greeter.SayHello ``` -------------------------------- ### Enable gRPC-Go Logging Source: https://github.com/grpc/grpc-go/blob/master/README.md Set environment variables to control the verbosity and severity of gRPC-Go logging. Set GRPC_GO_LOG_VERBOSITY_LEVEL to 99 for maximum verbosity and GRPC_GO_LOG_SEVERITY_LEVEL to 'info' for informational messages. ```sh export GRPC_GO_LOG_VERBOSITY_LEVEL=99 export GRPC_GO_LOG_SEVERITY_LEVEL=info ``` -------------------------------- ### Create ALTS Client Credentials Source: https://github.com/grpc/grpc-go/blob/master/examples/features/encryption/README.md Generate ALTS client credentials using default options. ALTS simplifies certificate management and is suitable for GCP environments. ```go alts.NewClientCreds(alts.DefaultClientOptions()) ``` -------------------------------- ### Create Metadata from Map Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md Use the `metadata.New` function to create a new metadata object from a `map[string]string`. Keys are automatically converted to lowercase. ```go md := metadata.New(map[string]string{"key1": "val1", "key2": "val2"}) ``` -------------------------------- ### Run Benchmark with Multiple Payload Curve Files Source: https://github.com/grpc/grpc-go/blob/master/Documentation/benchmark.md Execute benchmarks with combinations of different request and response payload size distributions. The utility runs a separate benchmark for each unique combination of specified CSV files. ```bash $ go run google.golang.org/grpc/benchmark/benchmain/main.go \ -workloads=unary \ -reqPayloadCurveFiles=/path/to/csv1,/path/to/csv2 \ -respPayloadCurveFiles=/path/to/csv3,/path/to/csv4 ``` -------------------------------- ### Describe a Specific gRPC Service Source: https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md Use grpcurl with the -plaintext flag and the full service name to inspect the service definition, including its methods. ```sh grpcurl -plaintext localhost:50051 describe helloworld.Greeter ``` -------------------------------- ### Enable TLS on gRPC Client Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-auth-support.md Use `grpc.NewClient` with `grpc.WithTransportCredentials` to enable TLS on a gRPC client. Pass `nil` for the certificate and empty string for the server name if using system-trusted certificates. ```go conn, err := grpc.NewClient(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""))) ``` -------------------------------- ### Define Simple RPC Method Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Define a simple RPC method using 'rpc' keyword, specifying request and response types. This is similar to a standard function call. ```proto // Obtains the feature at a given position. rpc GetFeature(Point) returns (Feature) {} ``` -------------------------------- ### Client-Side Compression Dial Options (Deprecated) Source: https://github.com/grpc/grpc-go/blob/master/Documentation/compression.md Deprecated functions for configuring client-side compression. `WithCompressor` applies a specific compressor implementation, while `WithDecompressor` handles incoming responses. ```go func WithCompressor(grpc.Compressor) DialOption {} ``` ```go func WithDecompressor(grpc.Decompressor) DialOption {} ``` -------------------------------- ### Call Simple gRPC Method Source: https://github.com/grpc/grpc-go/blob/master/examples/gotutorial.md Invokes a simple RPC method on the gRPC client stub. Pass a `context.Context` and the request protocol buffer object. The call is synchronous and returns a response or an error. ```go feature, err := client.GetFeature(ctx, &pb.Point{409146138, -746188906}) if err != nil { ... } ``` ```go log.Println(feature) ``` -------------------------------- ### Authenticate with JWT Service Account Source: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-auth-support.md Authenticate using a JWT from a service account file by creating credentials with `oauth.NewServiceAccountFromFile` and passing them to `grpc.NewClient` along with TLS transport credentials. ```go jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope) if err != nil { log.Fatalf("Failed to create JWT credentials: %v", err) } conn, err := grpc.NewClient(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(jwtCreds)) ```