grpc

package
v1.67.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 11 Imported by: 0

README

Package grpc

Пакет grpc предоставляет инструменты для создания и управления gRPC-серверами, включая обработку аутентификации, маршрутизацию запросов и интеграцию с метаданными. Поддерживает гибкую настройку обработчиков, безопасное обновление сервисов и работу с заголовками.

Types

Server

gRPC-сервер с поддержкой динамического обновления обработчиков.

Methods:

DefaultServer(restOptions ...grpc.ServerOption) *Server

Создать gRPC-сервер с настройками по умолчанию (максимальный размер сообщения 64 МБ).

NewServer(opts ...grpc.ServerOption) *Server

Создать кастомный сервер с указанными опциями gRPC.

(s *Server) Upgrade(service isp.BackendServiceServer)

Атомарно обновить обработчик сервиса без остановки сервера.

(s *Server) ListenAndServe(address string) error

Запустить сервер на указанном адресе.

(s *Server) Serve(listener net.Listener) error

Запустить сервер на существующем listener.

(s *Server) Shutdown()

Остановить сервер

Mux

Мультиплексор для маршрутизации gRPC-запросов. Регистрирует обработчики по имени эндпоинта.

Methods:

NewMux() *Mux

Создать новый мультиплексор.

(m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux

Зарегистрировать обработчик для указанного эндпоинта.

(m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error)

Обрабатывает входящий запрос, определяя эндпоинт через заголовок ProxyMethodNameHeader.

AuthData

Структура для работы с метаданными аутентификации в gRPC-запросах. Оборачивает metadata.MD и предоставляет методы для извлечения идентификаторов из заголовков.

Methods:

(i AuthData) SystemId() (int, error)

Получить идентификатор системы из заголовка x-system-identity.

(i AuthData) DomainId() (int, error)

Получить идентификатор домена из заголовка x-domain-identity.

(i AuthData) ServiceId() (int, error)

Получить идентификатор сервиса из заголовка x-service-identity.

(i AuthData) ApplicationId() (int, error)

Получить идентификатор системы из заголовка x-application-identity.

(i AuthData) ApplicationName() (int, error)

Получить название системы из заголовка x-application-name.

(i AuthData) UserId() (int, error)

Получить идентификатор пользователя из заголовка x-user-identity.

(i AuthData) DeviceId() (int, error)

Получить идентификатор устройства из заголовка x-device-identity.

(i AuthData) UserToken() (string, error)

Получить токен пользователя из заголовка x-user-token.

(i AuthData) DeviceToken() (string, error)

Получить токен устройства из заголовка x-device-token.

Functions

StringFromMd(key string, md metadata.MD) (string, error)

Извлекает строковое значение из метаданных по ключу.

IntFromMd(key string, md metadata.MD) (int, error)

Извлекает целочисленное значение из метаданных по ключу.

Usage

Default usage flow
package main

import (
	"context"
	"log"

	"github.com/txix-open/isp-kit/grpc"
	"github.com/txix-open/isp-kit/grpc/isp"
	"github.com/txix-open/isp-kit/shutdown"
)

func main() {
	mux := grpc.NewMux()
	mux.Handle("/get_users", func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
		/* put here business logic */
		return new(isp.Message), nil
	})

	srv := grpc.DefaultServer()
	srv.Upgrade(mux)

	shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
		log.Println("shutting down...")
		srv.Shutdown()
		log.Println("shutdown completed")
	})

	err := srv.ListenAndServe(":8080")
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package grpc provides a gRPC server and client implementation for the ISP kit framework. It enables building scalable microservices with support for hot-swappable handlers, middleware integration, and structured authentication via metadata.

The package supports both unary and streaming RPCs, with built-in features for request/response logging, metrics collection, and distributed tracing.

Index

Constants

View Source
const (
	// ApplicationIdHeader is the metadata key for application identity.
	ApplicationIdHeader = "x-application-identity"
	// ApplicationNameHeader is the metadata key for application name.
	ApplicationNameHeader = "x-application-name"
	// UserIdHeader is the metadata key for user identity.
	UserIdHeader = "x-user-identity"
	// DeviceIdHeader is the metadata key for device identity.
	DeviceIdHeader = "x-device-identity"
	// ServiceIdHeader is the metadata key for service identity.
	ServiceIdHeader = "x-service-identity"
	// DomainIdHeader is the metadata key for domain identity.
	DomainIdHeader = "x-domain-identity"
	// SystemIdHeader is the metadata key for system identity.
	SystemIdHeader = "x-system-identity"
	// UserTokenHeader is the metadata key for user token.
	UserTokenHeader = "x-user-token"
	// DeviceTokenHeader is the metadata key for device token.
	DeviceTokenHeader = "x-device-token"
)
View Source
const (
	// DefaultMaxSizeByte defines the default maximum message size in bytes (64MB).
	DefaultMaxSizeByte = 64 * 1024 * 1024
)
View Source
const (
	// ProxyMethodNameHeader is the metadata key used to specify the target endpoint.
	ProxyMethodNameHeader = "proxy_method_name"
)

Variables

This section is empty.

Functions

func IntFromMd added in v1.64.4

func IntFromMd(key string, md metadata.MD) (int, error)

IntFromMd extracts an integer value from metadata by key. Returns an error if the key is not found or the value cannot be parsed as an integer.

func StringFromMd

func StringFromMd(key string, md metadata.MD) (string, error)

StringFromMd extracts a string value from metadata by key. Returns an error if metadata is nil or the key is not found.

Types

type AuthData

type AuthData metadata.MD

AuthData wraps metadata.MD to provide structured access to authentication and authorization information from gRPC request metadata. All methods return an error if the key is not found or cannot be parsed.

func (AuthData) ApplicationId

func (i AuthData) ApplicationId() (int, error)

ApplicationId extracts the application identity from metadata as an integer. Returns an error if the key is not found or the value cannot be parsed as an integer.

func (AuthData) ApplicationName added in v1.64.4

func (i AuthData) ApplicationName() (string, error)

ApplicationName extracts the application name from metadata as a string. Returns an error if the key is not found.

func (AuthData) DeviceId

func (i AuthData) DeviceId() (int, error)

DeviceId extracts the device identity from metadata as an integer. Returns an error if the key is not found or the value cannot be parsed as an integer.

func (AuthData) DeviceToken

func (i AuthData) DeviceToken() (string, error)

DeviceToken extracts the device token from metadata as a string. Returns an error if the key is not found.

func (AuthData) DomainId

func (i AuthData) DomainId() (int, error)

DomainId extracts the domain identity from metadata as an integer. Returns an error if the key is not found or the value cannot be parsed as an integer.

func (AuthData) ServiceId

func (i AuthData) ServiceId() (int, error)

ServiceId extracts the service identity from metadata as an integer. Returns an error if the key is not found or the value cannot be parsed as an integer.

func (AuthData) SystemId

func (i AuthData) SystemId() (int, error)

SystemId extracts the system identity from metadata as an integer. Returns an error if the key is not found or the value cannot be parsed as an integer.

func (AuthData) UserId

func (i AuthData) UserId() (int, error)

UserId extracts the user identity from metadata as an integer. Returns an error if the key is not found or the value cannot be parsed as an integer.

func (AuthData) UserToken

func (i AuthData) UserToken() (string, error)

UserToken extracts the user token from metadata as a string. Returns an error if the key is not found.

type HandlerFunc

type HandlerFunc func(ctx context.Context, message *isp.Message) (*isp.Message, error)

HandlerFunc defines the signature for gRPC request handlers. Receives a context and message, returns a response message and optional error.

type Middleware

type Middleware func(next HandlerFunc) HandlerFunc

Middleware wraps a HandlerFunc to add cross-cutting concerns like logging, metrics, authentication, or error handling. Middleware functions are typically chained in reverse order of execution.

type Mux

type Mux struct {
	isp.UnimplementedBackendServiceServer
	// contains filtered or unexported fields
}

Mux is a request router that dispatches gRPC requests to registered handlers based on endpoint name. It extracts the endpoint from request metadata and invokes the corresponding HandlerFunc. Mux implements the BackendServiceServer interface but does not support streaming RPCs.

func NewMux

func NewMux() *Mux

NewMux creates a new Mux with an empty handler registry.

func (*Mux) Handle

func (m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux

Handle registers a HandlerFunc for the specified endpoint. Panics if a handler is already registered for the endpoint. Returns the Mux for method chaining.

func (*Mux) Request

func (m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error)

Request handles unary gRPC requests by routing to the registered handler for the endpoint. The endpoint is extracted from the ProxyMethodNameHeader in request metadata. Returns an error if metadata is missing, endpoint is not found, or handler fails.

func (*Mux) RequestStream

func (m *Mux) RequestStream(_ isp.BackendService_RequestStreamServer) error

RequestStream returns an unimplemented error for streaming RPCs. Mux does not support streaming; use a custom implementation for streaming support.

type Server

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

Server wraps a gRPC server with hot-swappable handler support. It provides a clean interface for starting, stopping, and upgrading gRPC services without requiring server restart.

func DefaultServer

func DefaultServer(restOptions ...grpc.ServerOption) *Server

DefaultServer creates a new Server with default configuration including 64MB message size limits. Accepts additional grpc.ServerOption for further customization. Thread-safe for concurrent use.

func NewServer

func NewServer(opts ...grpc.ServerOption) *Server

NewServer creates a new Server with custom gRPC options. Accepts variadic grpc.ServerOption for full configuration control. Thread-safe for concurrent use.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(address string) error

ListenAndServe binds the server to the specified TCP address and starts serving. Returns an error if binding fails or serving encounters a fatal error.

func (*Server) Serve

func (s *Server) Serve(listener net.Listener) error

Serve starts serving gRPC requests on the provided listener. Blocks until the server is stopped or an error occurs. Returns an error if serving encounters a fatal error.

func (*Server) Shutdown

func (s *Server) Shutdown()

Shutdown gracefully stops the server, waiting for in-flight requests to complete. Thread-safe for concurrent use.

func (*Server) Upgrade

func (s *Server) Upgrade(service isp.BackendServiceServer)

Upgrade atomically replaces the backend service handler without interrupting in-flight requests. This enables hot-reload of business logic without server restart. Thread-safe for concurrent use.

Directories

Path Synopsis
Package apierrors provides structured error handling for gRPC services.
Package apierrors provides structured error handling for gRPC services.
Package client provides a gRPC client implementation with built-in load balancing, middleware support, and observability features.
Package client provides a gRPC client implementation with built-in load balancing, middleware support, and observability features.
request
Package request provides a fluent builder for constructing and executing gRPC requests.
Package request provides a fluent builder for constructing and executing gRPC requests.
Package endpoint provides a higher-level abstraction for building gRPC handlers.
Package endpoint provides a higher-level abstraction for building gRPC handlers.
grpclog
Package grpclog provides logging middleware for gRPC server handlers.
Package grpclog provides logging middleware for gRPC server handlers.

Jump to

Keyboard shortcuts

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