grpc

package
v0.9.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package grpc provides a fluent API for building gRPC servers and HTTP gateways.

The package follows Velocity's patterns:

  • Interface-first design with pluggable auth validators
  • Global singleton with GetServer() function
  • Auto-init from environment variables
  • Builder pattern for configuration

Basic usage:

server := grpc.NewServer(
    grpc.WithPort("50051"),
    grpc.WithReflection(true),
)
server.Use(grpc.RecoveryInterceptor(), grpc.LoggingInterceptor())
server.RegisterService(&myService{})
server.Start()

Index

Constants

View Source
const (
	ProtocolGRPC = grpcevents.ProtocolGRPC
	ProtocolHTTP = grpcevents.ProtocolHTTP
)

Protocol constants

Variables

View Source
var (
	ErrUnauthenticated    = status.Error(codes.Unauthenticated, "authentication required")
	ErrPermissionDenied   = status.Error(codes.PermissionDenied, "permission denied")
	ErrNotFound           = status.Error(codes.NotFound, "resource not found")
	ErrAlreadyExists      = status.Error(codes.AlreadyExists, "resource already exists")
	ErrInvalidArgument    = status.Error(codes.InvalidArgument, "invalid argument")
	ErrInternal           = status.Error(codes.Internal, "internal server error")
	ErrUnimplemented      = status.Error(codes.Unimplemented, "not implemented")
	ErrUnavailable        = status.Error(codes.Unavailable, "service unavailable")
	ErrResourceExhausted  = status.Error(codes.ResourceExhausted, "resource exhausted")
	ErrFailedPrecondition = status.Error(codes.FailedPrecondition, "failed precondition")
	ErrAborted            = status.Error(codes.Aborted, "operation aborted")
	ErrDeadlineExceeded   = status.Error(codes.DeadlineExceeded, "deadline exceeded")
	ErrCancelled          = status.Error(codes.Canceled, "operation cancelled")
)

Common gRPC errors with standard messages

View Source
var (
	ErrServerNotInitialized  = errors.New("grpc server not initialized")
	ErrGatewayNotInitialized = errors.New("grpc gateway not initialized")
	ErrInvalidPort           = errors.New("invalid port")
	ErrServerAlreadyRunning  = errors.New("server already running")
	ErrNoEndpoint            = errors.New("no grpc endpoint configured for gateway")
)

Common errors

Functions

func AlreadyExists

func AlreadyExists(msg string) error

AlreadyExists creates an already exists error with a custom message

func Code

func Code(err error) codes.Code

Code extracts the gRPC status code from an error. Returns codes.OK if the error is nil. Returns codes.Unknown if the error is not a gRPC status error.

func ContextWithClaims

func ContextWithClaims(ctx context.Context, claims Claims) context.Context

ContextWithClaims adds claims to the context. This is a convenience wrapper around interceptors.ContextWithClaims.

func ContextWithMethod

func ContextWithMethod(ctx context.Context, method string) context.Context

ContextWithMethod adds the gRPC method to the context

func ContextWithRequestID

func ContextWithRequestID(ctx context.Context, requestID string) context.Context

ContextWithRequestID adds a request ID to the context

func DispatchEvent

func DispatchEvent(event interface{})

DispatchEvent dispatches an event if a dispatcher is configured

func ErrorIs

func ErrorIs(err, target error) bool

ErrorIs checks if a gRPC error matches a target error by comparing codes and messages

func ExtractAllMetadata

func ExtractAllMetadata(ctx context.Context, key string) []string

ExtractAllMetadata extracts all values for a metadata key. Returns nil if not found.

func ExtractBearerToken

func ExtractBearerToken(ctx context.Context) string

ExtractBearerToken extracts a bearer token from gRPC metadata. Returns empty string if no token is found.

func ExtractMetadata

func ExtractMetadata(ctx context.Context, key string) string

ExtractMetadata extracts a specific metadata value from context. Returns empty string if not found.

func FailedPrecondition

func FailedPrecondition(msg string) error

FailedPrecondition creates a failed precondition error with a custom message

func FromError

func FromError(err error) *status.Status

FromError converts a standard Go error to a gRPC status. This is useful for extracting code and message from errors.

func GenerateRequestID

func GenerateRequestID() string

GenerateRequestID generates a new request ID

func Initialize

func Initialize() error

Initialize sets up the default server and gateway from environment. Call this at application startup if you want to use the global instances.

func Internal

func Internal(msg string) error

Internal creates an internal error with a custom message

func Internalf

func Internalf(format string, args ...interface{}) error

Internalf creates an internal error with a formatted message

func InvalidArgument

func InvalidArgument(msg string) error

InvalidArgument creates an invalid argument error with a custom message

func InvalidArgumentf

func InvalidArgumentf(format string, args ...interface{}) error

InvalidArgumentf creates an invalid argument error with a formatted message

func IsCode

func IsCode(err error, code codes.Code) bool

IsCode checks if an error has a specific gRPC status code

func IsInternal

func IsInternal(err error) bool

IsInternal checks if an error is an Internal error

func IsInvalidArgument

func IsInvalidArgument(err error) bool

IsInvalidArgument checks if an error is an InvalidArgument error

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if an error is a NotFound error

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied checks if an error is a PermissionDenied error

func IsUnauthenticated

func IsUnauthenticated(err error) bool

IsUnauthenticated checks if an error is an Unauthenticated error

func IsUnavailable

func IsUnavailable(err error) bool

IsUnavailable checks if an error is an Unavailable error

func Message

func Message(err error) string

Message extracts the message from a gRPC status error. Returns empty string if the error is nil. Returns the error string if it's not a gRPC status error.

func MethodFromContext

func MethodFromContext(ctx context.Context) string

MethodFromContext extracts the gRPC method from the context. Returns empty string if no method is present.

func NewError

func NewError(code codes.Code, msg string) error

NewError creates a new gRPC status error with the given code and message

func NewErrorf

func NewErrorf(code codes.Code, format string, args ...interface{}) error

NewErrorf creates a new gRPC status error with a formatted message

func NotFound

func NotFound(msg string) error

NotFound creates a not found error with a custom message

func NotFoundf

func NotFoundf(format string, args ...interface{}) error

NotFoundf creates a not found error with a formatted message

func PermissionDenied

func PermissionDenied(msg string) error

PermissionDenied creates a permission denied error with a custom message

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext extracts the request ID from the context. Returns empty string if no request ID is present.

func Reset

func Reset()

Reset resets the global instances. Useful for testing.

func ResourceExhausted

func ResourceExhausted(msg string) error

ResourceExhausted creates a resource exhausted error with a custom message

func SetEventDispatcher

func SetEventDispatcher(dispatcher func(event interface{}) error)

SetEventDispatcher sets the event dispatcher function. This is called by the events package to wire up event dispatching.

func SetGateway

func SetGateway(g *Gateway)

SetGateway sets the default gateway instance. Useful for testing or custom initialization.

func SetServer

func SetServer(s *Server)

SetServer sets the default server instance. Useful for testing or custom initialization.

func TeamIDFromContext

func TeamIDFromContext(ctx context.Context) uint

TeamIDFromContext extracts the team ID from context claims. Returns 0 if no claims are present.

func Unauthenticated

func Unauthenticated(msg string) error

Unauthenticated creates an unauthenticated error with a custom message

func Unavailable

func Unavailable(msg string) error

Unavailable creates an unavailable error with a custom message

func UserIDFromContext

func UserIDFromContext(ctx context.Context) uint

UserIDFromContext extracts the user ID from context claims. Returns 0 if no claims are present.

func WrapError

func WrapError(err error) error

WrapError wraps a Go error in a gRPC status error. If the error is already a gRPC status error, it is returned unchanged. Otherwise, it's wrapped as an internal error with a generic message (the real error is logged server-side). In debug mode, the original message is preserved for developer convenience.

func WrapErrorWithCode

func WrapErrorWithCode(err error, code codes.Code) error

WrapErrorWithCode wraps a Go error with a specific gRPC code. If the error is already a gRPC status error, it is returned unchanged. For Internal/Unknown codes, the raw message is hidden from clients unless debug mode is enabled.

Types

type AuthFailed

type AuthFailed = grpcevents.AuthFailed

Re-export event types from grpcevents package for convenience

type BasicClaims

type BasicClaims = interceptors.BasicClaims

BasicClaims is a simple implementation of the Claims interface

type Claims

type Claims = interceptors.Claims

Claims represents authenticated user claims. Applications can implement this interface with their own claims structure.

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) Claims

ClaimsFromContext extracts claims from the context. Returns nil if no claims are present. This is a convenience wrapper around interceptors.ClaimsFromContext.

func MustClaimsFromContext

func MustClaimsFromContext(ctx context.Context) Claims

MustClaimsFromContext extracts claims from the context. Panics if no claims are present.

type Config

type Config struct {
	// Server configuration
	ServerPort       string
	EnableReflection bool
	MaxRecvMsgSize   int
	MaxSendMsgSize   int

	// Gateway configuration
	GatewayPort  string
	GRPCEndpoint string
}

Config holds gRPC configuration loaded from environment

func LoadConfig

func LoadConfig() *Config

LoadConfig loads gRPC configuration from environment variables:

  • GRPC_PORT: gRPC server port (default: 50051)
  • GRPC_REFLECTION: Enable reflection (default: false)
  • GRPC_MAX_RECV_SIZE: Max receive message size in bytes (default: 4MB)
  • GRPC_MAX_SEND_SIZE: Max send message size in bytes (default: 4MB)
  • GATEWAY_PORT: HTTP gateway port (default: 8080)
  • GRPC_ENDPOINT: gRPC endpoint for gateway (default: localhost:50051)

type Gateway

type Gateway struct {
	// contains filtered or unexported fields
}

Gateway wraps an HTTP gateway that proxies to a gRPC server

func GetGateway

func GetGateway() *Gateway

GetGateway returns the default HTTP gateway instance. Initializes from environment if not already initialized.

func NewGateway

func NewGateway(opts ...GatewayOption) *Gateway

NewGateway creates a new HTTP gateway with the given options

func (*Gateway) Address

func (g *Gateway) Address() string

Address returns the address the gateway is listening on

func (*Gateway) Build

func (g *Gateway) Build(ctx context.Context) error

Build constructs the HTTP gateway with all configured handlers. This is called automatically by Start() if not called explicitly.

func (*Gateway) GRPCEndpoint

func (g *Gateway) GRPCEndpoint() string

GRPCEndpoint returns the configured gRPC endpoint

func (*Gateway) IsRunning

func (g *Gateway) IsRunning() bool

IsRunning returns true if the gateway is currently running

func (*Gateway) Mux

func (g *Gateway) Mux() *runtime.ServeMux

Mux returns the underlying runtime.ServeMux. Returns nil if the gateway hasn't been built yet.

func (*Gateway) Port

func (g *Gateway) Port() string

Port returns the configured port

func (*Gateway) RegisterHandler

func (g *Gateway) RegisterHandler(handler GatewayRegistrationFunc) *Gateway

RegisterHandler registers a gRPC-Gateway handler with the gateway. The handler function should match the pattern generated by grpc-gateway:

gateway.RegisterHandler(pb.RegisterMyServiceHandlerFromEndpoint)

func (*Gateway) Shutdown

func (g *Gateway) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the HTTP gateway

func (*Gateway) Start

func (g *Gateway) Start() error

Start builds (if not already built) and starts the HTTP gateway. This method blocks until the server is stopped.

func (*Gateway) StartAsync

func (g *Gateway) StartAsync() error

StartAsync builds and starts the HTTP gateway in a goroutine. Returns immediately. Use Stop() or Shutdown() to stop the gateway.

func (*Gateway) StartAsyncWithContext

func (g *Gateway) StartAsyncWithContext(ctx context.Context) error

StartAsyncWithContext builds and starts the HTTP gateway in a goroutine with a context.

func (*Gateway) StartWithContext

func (g *Gateway) StartWithContext(ctx context.Context) error

StartWithContext builds and starts the HTTP gateway with a context.

func (*Gateway) Stop

func (g *Gateway) Stop()

Stop stops the HTTP gateway immediately

func (*Gateway) Use

func (g *Gateway) Use(middleware ...func(http.Handler) http.Handler) *Gateway

Use adds HTTP middleware to the gateway. Middleware is applied in the order added (outermost first).

type GatewayOption

type GatewayOption func(*Gateway)

GatewayOption configures the Gateway

func GatewayWithDialOption

func GatewayWithDialOption(opt grpc.DialOption) GatewayOption

GatewayWithDialOption adds a gRPC dial option

func GatewayWithGRPCEndpoint

func GatewayWithGRPCEndpoint(endpoint string) GatewayOption

GatewayWithGRPCEndpoint sets the gRPC server endpoint to proxy to

func GatewayWithInsecure

func GatewayWithInsecure() GatewayOption

GatewayWithInsecure explicitly configures the gateway to use insecure credentials. This should only be used for local development.

func GatewayWithMuxOption

func GatewayWithMuxOption(opt runtime.ServeMuxOption) GatewayOption

GatewayWithMuxOption adds a runtime.ServeMuxOption

func GatewayWithPort

func GatewayWithPort(port string) GatewayOption

GatewayWithPort sets the port for the HTTP gateway

func GatewayWithTLS added in v0.9.2

func GatewayWithTLS(certFile string) GatewayOption

GatewayWithTLS configures the gateway to use TLS credentials for the connection to the gRPC server. certFile is the CA certificate used to verify the server. If certFile is empty, the system certificate pool is used.

type GatewayRegistrationFunc

type GatewayRegistrationFunc func(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) error

GatewayRegistrationFunc is called to register handlers with the gateway

type GatewayStarted

type GatewayStarted = grpcevents.GatewayStarted

Re-export event types from grpcevents package for convenience

type GatewayStopped

type GatewayStopped = grpcevents.GatewayStopped

Re-export event types from grpcevents package for convenience

type HandlerRegistrationFunc

type HandlerRegistrationFunc func(gateway interface{}) error

HandlerRegistrationFunc is a function type for registering HTTP handlers with a gateway. This matches the pattern used by grpc-gateway generated code:

pb.RegisterMyServiceHandlerFromEndpoint(ctx, mux, endpoint, opts)

type HealthChecker

type HealthChecker func(ctx context.Context) error

HealthChecker is a function that performs a health check. Returns nil if healthy, or an error describing the issue.

type HealthService

type HealthService struct {
	grpc_health_v1.UnimplementedHealthServer
	// contains filtered or unexported fields
}

HealthService implements the gRPC Health checking protocol. See: https://github.com/grpc/grpc/blob/master/doc/health-checking.md

func NewHealthService

func NewHealthService() *HealthService

NewHealthService creates a new health service

func (*HealthService) Check

Check implements the Health.Check RPC

func (*HealthService) GetStatus

GetStatus returns the current status for a service

func (*HealthService) Register

func (s *HealthService) Register(server *grpc.Server)

Register registers the health service with a gRPC server

func (*HealthService) RegisterChecker

func (s *HealthService) RegisterChecker(service string, checker HealthChecker)

RegisterChecker registers a dynamic health checker for a service. The checker is called on each health check request.

func (*HealthService) RegistrationFunc

func (s *HealthService) RegistrationFunc() RegistrationFunc

RegistrationFunc returns a registration function for use with Server.RegisterService

func (*HealthService) RemoveChecker

func (s *HealthService) RemoveChecker(service string)

RemoveChecker removes a dynamic health checker for a service

func (*HealthService) SetNotServing

func (s *HealthService) SetNotServing(service string)

SetNotServing marks a service as not serving

func (*HealthService) SetServing

func (s *HealthService) SetServing(service string)

SetServing marks a service as serving

func (*HealthService) SetServingStatus

func (s *HealthService) SetServingStatus(service string, status grpc_health_v1.HealthCheckResponse_ServingStatus)

SetServingStatus sets the serving status for a service

func (*HealthService) Watch

Watch implements the Health.Watch RPC for streaming health checks. This is a simple implementation that sends the current status and then blocks.

type InterceptorPair

type InterceptorPair struct {
	Unary  grpc.UnaryServerInterceptor
	Stream grpc.StreamServerInterceptor
}

InterceptorPair holds both unary and stream interceptor variants. Many interceptors need both variants, so this groups them together.

type MethodDesc

type MethodDesc struct {
	MethodName string
	Handler    interface{}
}

MethodDesc describes a unary method

type PanicRecovered

type PanicRecovered = grpcevents.PanicRecovered

Re-export event types from grpcevents package for convenience

type Protocol

type Protocol = grpcevents.Protocol

Protocol type re-export

type RegistrationFunc

type RegistrationFunc func(server interface{})

RegistrationFunc is a function type for registering a service with a gRPC server. This matches the pattern used by generated protobuf code:

pb.RegisterMyServiceServer(grpcServer, &myServiceImpl{})

type RequestCompleted

type RequestCompleted = grpcevents.RequestCompleted

Re-export event types from grpcevents package for convenience

type RequestFailed

type RequestFailed = grpcevents.RequestFailed

Re-export event types from grpcevents package for convenience

type RequestStarted

type RequestStarted = grpcevents.RequestStarted

Re-export event types from grpcevents package for convenience

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server wraps a gRPC server with Velocity patterns

func GetServer

func GetServer() *Server

GetServer returns the default gRPC server instance. Initializes from environment if not already initialized.

func NewServer

func NewServer(opts ...ServerOption) *Server

NewServer creates a new gRPC server with the given options

func (*Server) Address

func (s *Server) Address() string

Address returns the address the server is listening on. Returns empty string if server hasn't been built yet.

func (*Server) Build

func (s *Server) Build() error

Build constructs the gRPC server with all configured options. This is called automatically by Start() if not called explicitly.

func (*Server) GRPCServer

func (s *Server) GRPCServer() *grpc.Server

GRPCServer returns the underlying *grpc.Server. Returns nil if the server hasn't been built yet.

func (*Server) GracefulStop

func (s *Server) GracefulStop()

GracefulStop gracefully stops the gRPC server

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning returns true if the server is currently running

func (*Server) Port

func (s *Server) Port() string

Port returns the configured port

func (*Server) RegisterService

func (s *Server) RegisterService(regFunc RegistrationFunc) *Server

RegisterService registers a service with the server using a registration function. The registration function receives the underlying *grpc.Server.

Example:

server.RegisterService(func(srv interface{}) {
    pb.RegisterMyServiceServer(srv.(*grpc.Server), &myService{})
})

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully stops the server with a context deadline

func (*Server) Start

func (s *Server) Start() error

Start builds (if not already built) and starts the gRPC server. This method blocks until the server is stopped.

func (*Server) StartAsync

func (s *Server) StartAsync() error

StartAsync builds and starts the gRPC server in a goroutine. Returns immediately. Use Stop() or GracefulStop() to stop the server.

func (*Server) Stop

func (s *Server) Stop()

Stop stops the gRPC server immediately

func (*Server) Use

func (s *Server) Use(interceptors ...grpc.UnaryServerInterceptor) *Server

Use adds unary interceptors to the server. Interceptors are executed in the order they are added.

func (*Server) UseAll

func (s *Server) UseAll(pairs ...InterceptorPair) *Server

UseAll adds both unary and stream interceptor pairs. This is convenient for interceptors that have both unary and stream variants.

func (*Server) UseStream

func (s *Server) UseStream(interceptors ...grpc.StreamServerInterceptor) *Server

UseStream adds stream interceptors to the server. Interceptors are executed in the order they are added.

type ServerOption

type ServerOption func(*Server)

ServerOption configures the Server

func WithMaxRecvMsgSize

func WithMaxRecvMsgSize(size int) ServerOption

WithMaxRecvMsgSize sets the maximum receive message size

func WithMaxSendMsgSize

func WithMaxSendMsgSize(size int) ServerOption

WithMaxSendMsgSize sets the maximum send message size

func WithPort

func WithPort(port string) ServerOption

WithPort sets the port for the gRPC server

func WithReflection

func WithReflection(enabled bool) ServerOption

WithReflection enables or disables gRPC reflection

func WithServerOption

func WithServerOption(opt grpc.ServerOption) ServerOption

WithServerOption adds a grpc.ServerOption to the server

type ServerStarted

type ServerStarted = grpcevents.ServerStarted

Re-export event types from grpcevents package for convenience

type ServerStopped

type ServerStopped = grpcevents.ServerStopped

Re-export event types from grpcevents package for convenience

type Service

type Service interface {
	// ServiceDesc returns the gRPC ServiceDesc for registration
	ServiceDesc() ServiceDescriptor
}

Service is an interface that all gRPC services should implement for registration with the server.

type ServiceDescriptor

type ServiceDescriptor struct {
	// ServiceName is the full name of the service (e.g., "mypackage.MyService")
	ServiceName string
	// HandlerType is the service interface type
	HandlerType interface{}
	// Handler is the actual service implementation
	Handler interface{}
	// Methods are the service methods
	Methods []MethodDesc
	// Streams are the streaming methods
	Streams []StreamDesc
}

ServiceDescriptor wraps the information needed to register a service

type StreamCompleted

type StreamCompleted = grpcevents.StreamCompleted

Re-export event types from grpcevents package for convenience

type StreamDesc

type StreamDesc struct {
	StreamName    string
	Handler       interface{}
	ServerStreams bool
	ClientStreams bool
}

StreamDesc describes a streaming method

type StreamFailed

type StreamFailed = grpcevents.StreamFailed

Re-export event types from grpcevents package for convenience

type StreamStarted

type StreamStarted = grpcevents.StreamStarted

Re-export event types from grpcevents package for convenience

Directories

Path Synopsis
Package converters provides utilities for converting between Go types and protobuf types.
Package converters provides utilities for converting between Go types and protobuf types.
Package grpcevents provides event types for gRPC operations.
Package grpcevents provides event types for gRPC operations.
Package interceptors provides gRPC interceptors for Velocity applications.
Package interceptors provides gRPC interceptors for Velocity applications.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL