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
- Variables
- func AlreadyExists(msg string) error
- func Code(err error) codes.Code
- func ContextWithClaims(ctx context.Context, claims Claims) context.Context
- func ContextWithMethod(ctx context.Context, method string) context.Context
- func ContextWithRequestID(ctx context.Context, requestID string) context.Context
- func DispatchEvent(event interface{})
- func ErrorIs(err, target error) bool
- func ExtractAllMetadata(ctx context.Context, key string) []string
- func ExtractBearerToken(ctx context.Context) string
- func ExtractMetadata(ctx context.Context, key string) string
- func FailedPrecondition(msg string) error
- func FromError(err error) *status.Status
- func GenerateRequestID() string
- func Initialize() error
- func Internal(msg string) error
- func Internalf(format string, args ...interface{}) error
- func InvalidArgument(msg string) error
- func InvalidArgumentf(format string, args ...interface{}) error
- func IsCode(err error, code codes.Code) bool
- func IsInternal(err error) bool
- func IsInvalidArgument(err error) bool
- func IsNotFound(err error) bool
- func IsPermissionDenied(err error) bool
- func IsUnauthenticated(err error) bool
- func IsUnavailable(err error) bool
- func Message(err error) string
- func MethodFromContext(ctx context.Context) string
- func NewError(code codes.Code, msg string) error
- func NewErrorf(code codes.Code, format string, args ...interface{}) error
- func NotFound(msg string) error
- func NotFoundf(format string, args ...interface{}) error
- func PermissionDenied(msg string) error
- func RequestIDFromContext(ctx context.Context) string
- func Reset()
- func ResourceExhausted(msg string) error
- func SetEventDispatcher(dispatcher func(event interface{}) error)
- func SetGateway(g *Gateway)
- func SetServer(s *Server)
- func TeamIDFromContext(ctx context.Context) uint
- func Unauthenticated(msg string) error
- func Unavailable(msg string) error
- func UserIDFromContext(ctx context.Context) uint
- func WrapError(err error) error
- func WrapErrorWithCode(err error, code codes.Code) error
- type AuthFailed
- type BasicClaims
- type Claims
- type Config
- type Gateway
- func (g *Gateway) Address() string
- func (g *Gateway) Build(ctx context.Context) error
- func (g *Gateway) GRPCEndpoint() string
- func (g *Gateway) IsRunning() bool
- func (g *Gateway) Mux() *runtime.ServeMux
- func (g *Gateway) Port() string
- func (g *Gateway) RegisterHandler(handler GatewayRegistrationFunc) *Gateway
- func (g *Gateway) Shutdown(ctx context.Context) error
- func (g *Gateway) Start() error
- func (g *Gateway) StartAsync() error
- func (g *Gateway) StartAsyncWithContext(ctx context.Context) error
- func (g *Gateway) StartWithContext(ctx context.Context) error
- func (g *Gateway) Stop()
- func (g *Gateway) Use(middleware ...func(http.Handler) http.Handler) *Gateway
- type GatewayOption
- func GatewayWithDialOption(opt grpc.DialOption) GatewayOption
- func GatewayWithGRPCEndpoint(endpoint string) GatewayOption
- func GatewayWithInsecure() GatewayOption
- func GatewayWithMuxOption(opt runtime.ServeMuxOption) GatewayOption
- func GatewayWithPort(port string) GatewayOption
- func GatewayWithTLS(certFile string) GatewayOption
- type GatewayRegistrationFunc
- type GatewayStarted
- type GatewayStopped
- type HandlerRegistrationFunc
- type HealthChecker
- type HealthService
- func (s *HealthService) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error)
- func (s *HealthService) GetStatus(service string) (grpc_health_v1.HealthCheckResponse_ServingStatus, bool)
- func (s *HealthService) Register(server *grpc.Server)
- func (s *HealthService) RegisterChecker(service string, checker HealthChecker)
- func (s *HealthService) RegistrationFunc() RegistrationFunc
- func (s *HealthService) RemoveChecker(service string)
- func (s *HealthService) SetNotServing(service string)
- func (s *HealthService) SetServing(service string)
- func (s *HealthService) SetServingStatus(service string, status grpc_health_v1.HealthCheckResponse_ServingStatus)
- func (s *HealthService) Watch(req *grpc_health_v1.HealthCheckRequest, ...) error
- type InterceptorPair
- type MethodDesc
- type PanicRecovered
- type Protocol
- type RegistrationFunc
- type RequestCompleted
- type RequestFailed
- type RequestStarted
- type Server
- func (s *Server) Address() string
- func (s *Server) Build() error
- func (s *Server) GRPCServer() *grpc.Server
- func (s *Server) GracefulStop()
- func (s *Server) IsRunning() bool
- func (s *Server) Port() string
- func (s *Server) RegisterService(regFunc RegistrationFunc) *Server
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) Start() error
- func (s *Server) StartAsync() error
- func (s *Server) Stop()
- func (s *Server) Use(interceptors ...grpc.UnaryServerInterceptor) *Server
- func (s *Server) UseAll(pairs ...InterceptorPair) *Server
- func (s *Server) UseStream(interceptors ...grpc.StreamServerInterceptor) *Server
- type ServerOption
- type ServerStarted
- type ServerStopped
- type Service
- type ServiceDescriptor
- type StreamCompleted
- type StreamDesc
- type StreamFailed
- type StreamStarted
Constants ¶
const ( ProtocolGRPC = grpcevents.ProtocolGRPC ProtocolHTTP = grpcevents.ProtocolHTTP )
Protocol constants
Variables ¶
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") 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
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 ¶
AlreadyExists creates an already exists error with a custom message
func 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 ¶
ContextWithClaims adds claims to the context. This is a convenience wrapper around interceptors.ContextWithClaims.
func ContextWithMethod ¶
ContextWithMethod adds the gRPC method to the context
func ContextWithRequestID ¶
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 ¶
ErrorIs checks if a gRPC error matches a target error by comparing codes and messages
func ExtractAllMetadata ¶
ExtractAllMetadata extracts all values for a metadata key. Returns nil if not found.
func ExtractBearerToken ¶
ExtractBearerToken extracts a bearer token from gRPC metadata. Returns empty string if no token is found.
func ExtractMetadata ¶
ExtractMetadata extracts a specific metadata value from context. Returns empty string if not found.
func FailedPrecondition ¶
FailedPrecondition creates a failed precondition error with a custom message
func FromError ¶
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 InvalidArgument ¶
InvalidArgument creates an invalid argument error with a custom message
func InvalidArgumentf ¶
InvalidArgumentf creates an invalid argument error with a formatted message
func IsInternal ¶
IsInternal checks if an error is an Internal error
func IsInvalidArgument ¶
IsInvalidArgument checks if an error is an InvalidArgument error
func IsPermissionDenied ¶
IsPermissionDenied checks if an error is a PermissionDenied error
func IsUnauthenticated ¶
IsUnauthenticated checks if an error is an Unauthenticated error
func IsUnavailable ¶
IsUnavailable checks if an error is an Unavailable error
func Message ¶
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 ¶
MethodFromContext extracts the gRPC method from the context. Returns empty string if no method is present.
func PermissionDenied ¶
PermissionDenied creates a permission denied error with a custom message
func RequestIDFromContext ¶
RequestIDFromContext extracts the request ID from the context. Returns empty string if no request ID is present.
func ResourceExhausted ¶
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 ¶
TeamIDFromContext extracts the team ID from context claims. Returns 0 if no claims are present.
func Unauthenticated ¶
Unauthenticated creates an unauthenticated error with a custom message
func Unavailable ¶
Unavailable creates an unavailable error with a custom message
func UserIDFromContext ¶
UserIDFromContext extracts the user ID from context claims. Returns 0 if no claims are present.
func WrapError ¶
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 ¶
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 ¶
ClaimsFromContext extracts claims from the context. Returns nil if no claims are present. This is a convenience wrapper around interceptors.ClaimsFromContext.
func MustClaimsFromContext ¶
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) Build ¶
Build constructs the HTTP gateway with all configured handlers. This is called automatically by Start() if not called explicitly.
func (*Gateway) GRPCEndpoint ¶
GRPCEndpoint returns the configured gRPC endpoint
func (*Gateway) Mux ¶
Mux returns the underlying runtime.ServeMux. Returns nil if the gateway hasn't been built yet.
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) Start ¶
Start builds (if not already built) and starts the HTTP gateway. This method blocks until the server is stopped.
func (*Gateway) StartAsync ¶
StartAsync builds and starts the HTTP gateway in a goroutine. Returns immediately. Use Stop() or Shutdown() to stop the gateway.
func (*Gateway) StartAsyncWithContext ¶
StartAsyncWithContext builds and starts the HTTP gateway in a goroutine with a context.
func (*Gateway) StartWithContext ¶
StartWithContext builds and starts the HTTP gateway with a context.
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 ¶
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 ¶
func (s *HealthService) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error)
Check implements the Health.Check RPC
func (*HealthService) GetStatus ¶
func (s *HealthService) GetStatus(service string) (grpc_health_v1.HealthCheckResponse_ServingStatus, bool)
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 ¶
func (s *HealthService) Watch(req *grpc_health_v1.HealthCheckRequest, stream grpc_health_v1.Health_WatchServer) error
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 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 ¶
Address returns the address the server is listening on. Returns empty string if server hasn't been built yet.
func (*Server) Build ¶
Build constructs the gRPC server with all configured options. This is called automatically by Start() if not called explicitly.
func (*Server) GRPCServer ¶
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) 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) Start ¶
Start builds (if not already built) and starts the gRPC server. This method blocks until the server is stopped.
func (*Server) StartAsync ¶
StartAsync builds and starts the gRPC server in a goroutine. Returns immediately. Use Stop() or GracefulStop() to stop the server.
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.
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 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
Source Files
¶
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. |