The Go implementation of gRPC: A high performance, open source, general RPC framework that puts mobile and HTTP/2 first
npx @tessl/cli install tessl/golang-grpc@1.77.0gRPC-Go is the Go implementation of gRPC: A high-performance, production-ready RPC framework that implements both client and server components with comprehensive support for creating distributed systems using Protocol Buffers and HTTP/2.
Name: google.golang.org/grpc
Type: Library
Language: Go
Version: 1.77.0
Installation:
go get google.golang.org/grpc@v1.77.0import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
)Define a service (using Protocol Buffers - see protobuf documentation):
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}Generate Go code:
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
helloworld.protoServer implementation:
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
pb "path/to/helloworld"
)
type server struct {
pb.UnimplementedGreeterServer
}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}Client implementation:
package main
import (
"context"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "path/to/helloworld"
)
func main() {
conn, err := grpc.NewClient("localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "world"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())
}grpc - Client/server creation, dialing, serving, streamingcodes, status - Error codes and status handlingmetadata, peer - Request metadata and peer informationcredentials/* - All authentication and authorization mechanismsbalancer/* - Load balancing policies and implementationsresolver/* - Service discovery and name resolutionstats, channelz, grpclog - Metrics, debugging, logginghealth, reflection, admin - Standard service implementationsencoding, keepalive, backoff, connectivity - Low-level configurationxds/* - Service mesh and xDS protocol supportThe foundation of gRPC-Go provides comprehensive client and server functionality with connection management, service registration, and RPC invocation.
Key APIs:
// Create a new client connection
func NewClient(target string, opts ...DialOption) (*ClientConn, error)
// ClientConn represents a virtual connection to a conceptual endpoint
type ClientConn struct {
// Has unexported fields
}
func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply any, opts ...CallOption) error
func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
func (cc *ClientConn) Close() error
func (cc *ClientConn) GetState() connectivity.State
// Create a new gRPC server
func NewServer(opt ...ServerOption) *Server
// Server is a gRPC server to serve RPC requests
type Server struct {
// Has unexported fields
}
func (s *Server) RegisterService(sd *ServiceDesc, ss any)
func (s *Server) Serve(lis net.Listener) error
func (s *Server) GracefulStop()
func (s *Server) Stop()See Client-Server Core for complete API documentation including all dial options, server options, connection management, and service registration.
gRPC supports four types of RPC patterns: unary (request-response), client streaming (many requests, one response), server streaming (one request, many responses), and bidirectional streaming (many requests, many responses).
Key APIs:
// Client-side streaming interfaces
type ClientStream interface {
Header() (metadata.MD, error)
Trailer() metadata.MD
CloseSend() error
Context() context.Context
SendMsg(m any) error
RecvMsg(m any) error
}
type ServerStreamingClient[Req any, Res any] interface {
Recv() (*Res, error)
ClientStream
}
type ClientStreamingClient[Req any, Res any] interface {
Send(*Req) error
CloseAndRecv() (*Res, error)
ClientStream
}
type BidiStreamingClient[Req any, Res any] interface {
Send(*Req) error
Recv() (*Res, error)
ClientStream
}
// Server-side streaming interfaces
type ServerStream interface {
SetHeader(metadata.MD) error
SendHeader(metadata.MD) error
SetTrailer(metadata.MD)
Context() context.Context
SendMsg(m any) error
RecvMsg(m any) error
}
type ServerStreamingServer[Req any, Res any] interface {
Send(*Res) error
ServerStream
}
type ClientStreamingServer[Req any, Res any] interface {
Recv() (*Req, error)
SendAndClose(*Res) error
ServerStream
}
type BidiStreamingServer[Req any, Res any] interface {
Recv() (*Req, error)
Send(*Res) error
ServerStream
}
// Stream descriptor
type StreamDesc struct {
StreamName string
Handler StreamHandler
ServerStreams bool
ClientStreams bool
}See Streaming for complete documentation on all streaming patterns, generic stream types, and stream lifecycle management.
Metadata provides a way to send and receive request/response headers and trailers. Context carries deadlines, cancellation signals, and request-scoped values.
Key APIs:
// Metadata operations
func SetHeader(ctx context.Context, md metadata.MD) error
func SendHeader(ctx context.Context, md metadata.MD) error
func SetTrailer(ctx context.Context, md metadata.MD) error
// CallOptions for metadata
func Header(md *metadata.MD) CallOption
func Trailer(md *metadata.MD) CallOption
// Context utilities
func Method(ctx context.Context) (string, bool)
func MethodFromServerStream(stream ServerStream) (string, bool)Metadata package (google.golang.org/grpc/metadata):
type MD map[string][]string
func New(m map[string]string) MD
func Pairs(kv ...string) MD
func Join(mds ...MD) MD
func (md MD) Append(k string, vals ...string) MD
func (md MD) Get(k string) []string
func (md MD) Set(k string, vals ...string)
func FromIncomingContext(ctx context.Context) (MD, bool)
func FromOutgoingContext(ctx context.Context) (MD, bool)
func NewIncomingContext(ctx context.Context, md MD) context.Context
func NewOutgoingContext(ctx context.Context, md MD) context.Context
func AppendToOutgoingContext(ctx context.Context, kv ...string) context.ContextSee Metadata and Context for complete documentation on metadata manipulation, context propagation, and peer information.
gRPC uses standardized status codes for errors. The status package provides rich error creation and manipulation.
Key APIs:
// Status package
type Status struct {
// Has unexported fields
}
func New(c codes.Code, msg string) *Status
func Newf(c codes.Code, format string, a ...any) *Status
func Error(c codes.Code, msg string) error
func Errorf(c codes.Code, format string, a ...any) error
func (s *Status) Err() error
func (s *Status) Code() codes.Code
func (s *Status) Message() string
func (s *Status) Details() []any
func (s *Status) WithDetails(details ...proto.Message) (*Status, error)
func FromError(err error) (s *Status, ok bool)
func Convert(err error) *Status
func Code(err error) codes.Code
// Standard codes
const (
OK Code = 0
Canceled Code = 1
Unknown Code = 2
InvalidArgument Code = 3
DeadlineExceeded Code = 4
NotFound Code = 5
AlreadyExists Code = 6
PermissionDenied Code = 7
ResourceExhausted Code = 8
FailedPrecondition Code = 9
Aborted Code = 10
OutOfRange Code = 11
Unimplemented Code = 12
Internal Code = 13
Unavailable Code = 14
DataLoss Code = 15
Unauthenticated Code = 16
)See Error Handling and Status Codes for complete documentation on error handling, status details, and error conversion.
gRPC provides comprehensive security mechanisms including TLS, OAuth2, JWT, ALTS, and custom credentials for both transport-level and per-RPC authentication.
Key APIs:
// Transport credentials (TLS)
type TransportCredentials interface {
ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
Info() ProtocolInfo
Clone() TransportCredentials
OverrideServerName(string) error
}
func NewTLS(c *tls.Config) TransportCredentials
func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials
func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error)
func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials
func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error)
// Insecure credentials (for testing)
func insecure.NewCredentials() credentials.TransportCredentials
// Per-RPC credentials
type PerRPCCredentials interface {
GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
RequireTransportSecurity() bool
}
// OAuth2 credentials
func oauth.NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials
func oauth.NewComputeEngine() credentials.PerRPCCredentials
func oauth.NewServiceAccountFromFile(filename string, scope ...string) (credentials.PerRPCCredentials, error)
// JWT credentials
func jwt.NewWithSignature(getSignature func() ([]byte, error), issuer string) (credentials.PerRPCCredentials, error)
// Dial/Server options for credentials
func WithTransportCredentials(creds credentials.TransportCredentials) DialOption
func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption
func Creds(c credentials.TransportCredentials) ServerOptionSee Credentials and Security for complete documentation on all credential types, TLS configuration, OAuth2, JWT, ALTS, and custom credentials.
gRPC supports multiple load balancing strategies including round-robin, pick-first, weighted round-robin, least request, and ring hash. Load balancers are pluggable and configurable.
Key APIs:
// Load balancer interface
type Balancer interface {
UpdateClientConnState(ClientConnState) error
ResolverError(error)
UpdateSubConnState(SubConn, SubConnState)
Close()
}
// Balancer builder
type Builder interface {
Build(cc ClientConn, opts BuildOptions) Balancer
Name() string
}
func Register(b Builder)
// Built-in balancers
const (
PickFirstBalancerName = "pick_first"
RoundRobinBalancerName = "round_robin"
)
// Service config for load balancing
func WithDefaultServiceConfig(s string) DialOption
// Example service config for round-robin
{
"loadBalancingConfig": [
{"round_robin": {}}
]
}Balancer packages:
balancer/roundrobin - Round-robin load balancingbalancer/pickfirst - Pick first available connectionbalancer/weightedroundrobin - Weighted round-robinbalancer/leastrequest - Least request load balancingbalancer/ringhash - Consistent hashingbalancer/weightedtarget - Weighted target selectionSee Load Balancing for complete documentation on all load balancing strategies, custom balancers, and configuration.
Name resolvers convert service names to network addresses and provide service discovery. gRPC supports DNS, manual, passthrough, and custom resolvers.
Key APIs:
// Resolver interface
type Builder interface {
Build(target Target, cc ClientConn, opts BuildOptions) (Resolver, error)
Scheme() string
}
type Resolver interface {
ResolveNow(ResolveNowOptions)
Close()
}
func Register(b Builder)
// Target URI format: scheme://authority/endpoint
// Built-in resolvers
import (
_ "google.golang.org/grpc/resolver/dns" // dns:/// resolver
"google.golang.org/grpc/resolver/manual" // manual:// resolver
_ "google.golang.org/grpc/resolver/passthrough" // passthrough:/// resolver
)
// Manual resolver for testing
r := manual.NewBuilderWithScheme("myscheme")
r.InitialState(resolver.State{
Addresses: []resolver.Address{
{Addr: "localhost:50051"},
{Addr: "localhost:50052"},
},
})
// Use custom resolvers with WithResolvers
func WithResolvers(rs ...resolver.Builder) DialOptionSee Name Resolution for complete documentation on all resolver types, custom resolvers, and service discovery patterns.
Interceptors provide middleware functionality for both unary and streaming RPCs on client and server sides. They enable cross-cutting concerns like logging, authentication, metrics, and tracing.
Key APIs:
// Client-side interceptors
type UnaryClientInterceptor func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error
type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error)
func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption
func WithStreamInterceptor(f StreamClientInterceptor) DialOption
func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption
func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption
// Server-side interceptors
type UnaryServerInterceptor func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (any, error)
type StreamServerInterceptor func(srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error
func UnaryInterceptor(i UnaryServerInterceptor) ServerOption
func StreamInterceptor(i StreamServerInterceptor) ServerOption
func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption
func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption
// Interceptor info types
type UnaryServerInfo struct {
Server any
FullMethod string
}
type StreamServerInfo struct {
FullMethod string
IsClientStream bool
IsServerStream bool
}See Interceptors for complete documentation on interceptor patterns, chaining, and common use cases.
The health checking service implements the gRPC Health Checking Protocol, allowing clients to query server health status per service.
Key APIs:
import (
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
)
// Create health server
healthServer := health.NewServer()
// Register with gRPC server
grpc_health_v1.RegisterHealthServer(s, healthServer)
// Set service status
healthServer.SetServingStatus("myservice", grpc_health_v1.HealthCheckResponse_SERVING)
healthServer.SetServingStatus("myservice", grpc_health_v1.HealthCheckResponse_NOT_SERVING)
// Client-side health checking
type HealthClient interface {
Check(ctx context.Context, in *HealthCheckRequest, opts ...CallOption) (*HealthCheckResponse, error)
Watch(ctx context.Context, in *HealthCheckRequest, opts ...CallOption) (Health_WatchClient, error)
}
// Health check response statuses
const (
HealthCheckResponse_UNKNOWN ServingStatus = 0
HealthCheckResponse_SERVING ServingStatus = 1
HealthCheckResponse_NOT_SERVING ServingStatus = 2
HealthCheckResponse_SERVICE_UNKNOWN ServingStatus = 3
)See Health Checking for complete documentation on health service implementation, client usage, and watch streams.
Server reflection enables clients to discover available services and their methods at runtime, useful for debugging tools like grpcurl and grpcui.
Key APIs:
import (
"google.golang.org/grpc/reflection"
)
// Register reflection service on a gRPC server
func Register(s ServiceInfoProvider)
// Example usage
s := grpc.NewServer()
// Register your services...
reflection.Register(s)
// Client-side reflection
import (
"google.golang.org/grpc/reflection/grpc_reflection_v1"
)
type ServerReflectionClient interface {
ServerReflectionInfo(ctx context.Context, opts ...CallOption) (ServerReflection_ServerReflectionInfoClient, error)
}
// Reflection requests
type ServerReflectionRequest struct {
Host string
MessageRequest isServerReflectionRequest_MessageRequest
// FileByFilename, FileContainingSymbol, FileContainingExtension,
// AllExtensionNumbersOfType, ListServices
}See Reflection for complete documentation on reflection service setup, client usage, and reflection protocol.
xDS enables integration with service mesh control planes (like Istio, Envoy) for dynamic configuration of routing, load balancing, and security policies.
Key APIs:
import (
"google.golang.org/grpc/xds"
)
// Create xDS-enabled gRPC server
func xds.NewGRPCServer(opts ...grpc.ServerOption) (*GRPCServer, error)
type GRPCServer struct {
*grpc.Server
}
func (s *GRPCServer) Serve(lis net.Listener) error
// Create xDS-enabled client
func grpc.NewClient(target string, opts ...DialOption) (*ClientConn, error)
// Use target format: "xds:///myservice"
// xDS bootstrap configuration
import "google.golang.org/grpc/xds/bootstrap"
type Config struct {
XDSServer ServerConfig
CertificateProviders map[string]CertificateProvider
ServerListenerResourceNameTemplate string
}
func NewConfig() (*Config, error)Supported xDS APIs:
See xDS Support for complete documentation on xDS configuration, server-side and client-side usage, and service mesh integration.
gRPC provides comprehensive observability through stats handlers, channelz for debugging, logging, and profiling support. OpenTelemetry integration is available for modern observability.
Key APIs:
// Stats handler interface
type Handler interface {
TagRPC(context.Context, *RPCTagInfo) context.Context
HandleRPC(context.Context, RPCStats)
TagConn(context.Context, *ConnTagInfo) context.Context
HandleConn(context.Context, ConnStats)
}
func WithStatsHandler(h stats.Handler) DialOption
func StatsHandler(h stats.Handler) ServerOption
// OpenTelemetry stats
import (
"google.golang.org/grpc/stats/opentelemetry"
)
func opentelemetry.Options() opentelemetry.Options
func opentelemetry.NewClientHandler(opts ...Option) (*ClientHandler, error)
func opentelemetry.NewServerHandler(opts ...Option) (*ServerHandler, error)
// Channelz for debugging
import (
"google.golang.org/grpc/channelz"
"google.golang.org/grpc/channelz/service"
)
// Register channelz service
service.RegisterChannelzServiceToServer(s)
type Identifier interface {
ID() int64
}
func GetTopChannels(id int64, maxResults int64) ([]*Channel, bool)
func GetServers(id int64, maxResults int64) ([]*Server, bool)
// Logging
import "google.golang.org/grpc/grpclog"
type LoggerV2 interface {
Info(args ...any)
Infoln(args ...any)
Infof(format string, args ...any)
Warning(args ...any)
Warningln(args ...any)
Warningf(format string, args ...any)
Error(args ...any)
Errorln(args ...any)
Errorf(format string, args ...any)
Fatal(args ...any)
Fataln(args ...any)
Fatalf(format string, args ...any)
V(l int) bool
}
func SetLoggerV2(l LoggerV2)
// Profiling
import "google.golang.org/grpc/profiling"
func Enable(enabled bool) errorSee Observability for complete documentation on stats handlers, OpenTelemetry integration, channelz debugging, logging configuration, and profiling.
Advanced features include compression, encoding, keepalive configuration, backoff parameters, connection attributes, and memory management.
Key APIs:
// Compression and encoding
import "google.golang.org/grpc/encoding"
type Codec interface {
Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v any) error
Name() string
}
func RegisterCodec(codec Codec)
func GetCodec(contentSubtype string) Codec
func UseCompressor(name string) CallOption
func CallContentSubtype(contentSubtype string) CallOption
// Keepalive
import "google.golang.org/grpc/keepalive"
type ClientParameters struct {
Time time.Duration
Timeout time.Duration
PermitWithoutStream bool
}
type ServerParameters struct {
MaxConnectionIdle time.Duration
MaxConnectionAge time.Duration
MaxConnectionAgeGrace time.Duration
Time time.Duration
Timeout time.Duration
}
type EnforcementPolicy struct {
MinTime time.Duration
PermitWithoutStream bool
}
func WithKeepaliveParams(kp ClientParameters) DialOption
func KeepaliveParams(kp ServerParameters) ServerOption
func KeepaliveEnforcementPolicy(kep EnforcementPolicy) ServerOption
// Backoff configuration
import "google.golang.org/grpc/backoff"
type Config struct {
BaseDelay time.Duration
Multiplier float64
Jitter float64
MaxDelay time.Duration
}
var DefaultConfig = Config{
BaseDelay: 1.0 * time.Second,
Multiplier: 1.6,
Jitter: 0.2,
MaxDelay: 120 * time.Second,
}
// Attributes
import "google.golang.org/grpc/attributes"
type Attributes struct {
// Has unexported fields
}
func New(m ...any) *Attributes
func (a *Attributes) Value(key any) any
func (a *Attributes) WithValue(key, value any) *Attributes
// Memory management
import "google.golang.org/grpc/mem"
type Buffer interface {
Len() int
ReadOnlyData() [][]byte
Ref()
Free()
}
type BufferSlice []Buffer
func (s BufferSlice) Len() int
func (s BufferSlice) Ref()
func (s BufferSlice) Free()See Advanced Features for complete documentation on compression, encoding, keepalive, backoff, attributes, peer information, tap, and memory management.
Admin services provide a convenient way to register multiple administrative services (channelz, CSDS) with a single call.
Key APIs:
import "google.golang.org/grpc/admin"
// Register admin services
func Register(s *grpc.Server) (cleanup func(), _ error)
// Registers:
// - Channelz service
// - Client Status Discovery Service (CSDS) if xDS is enabledSee Admin Services for complete documentation on admin service registration and usage.
gRPC provides utilities specifically designed for testing, including in-memory connections and manual resolvers.
Key APIs:
// In-memory buffer connection for testing
import "google.golang.org/grpc/test/bufconn"
func New(sz int) *Listener
type Listener struct {
// Has unexported fields
}
func (l *Listener) Accept() (net.Conn, error)
func (l *Listener) Close() error
func (l *Listener) Addr() net.Addr
func (l *Listener) Dial() (net.Conn, error)
// Example usage
const bufSize = 1024 * 1024
lis := bufconn.New(bufSize)
s := grpc.NewServer()
// Register services...
go s.Serve(lis)
conn, _ := grpc.NewClient("bufnet",
grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) {
return lis.Dial()
}),
grpc.WithTransportCredentials(insecure.NewCredentials()))
// Manual resolver for testing
import "google.golang.org/grpc/resolver/manual"
func NewBuilderWithScheme(scheme string) *Resolver
type Resolver struct {
*resolver.Builder
}
func (r *Resolver) InitialState(s resolver.State)
func (r *Resolver) UpdateState(s resolver.State) errorSee Testing Utilities for complete documentation on testing tools, mocking, and test patterns.
const Version = "1.77.0"