client

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: 17 Imported by: 0

README

Package client

Пакет client предоставляет гибкий gRPC-клиент с поддержкой балансировки нагрузки, middleware для логирования, метрик, трассировки и динамическим обновлением списка хостов.

Types

Client

Основная структура клиента для взаимодействия с gRPC-серверами. Поддерживает балансировку нагрузки, цепочки middleware и динамическое обновление списка хостов.

Methods:

New(initialHosts []string, opts ...Option) (*Client, error)

Создать новый клиент с указанными начальными хостами и опциями:

  • WithMiddlewares(middlewares ...request.Middleware) Option – добавить middleware в цепочку обработки запроса.
  • WithDialOptions(dialOptions ...grpc.DialOption) Option – опция для передачи параметров подключения gRPC (например, TLS, таймауты)
(cli *Client) Invoke(endpoint string) *request.Builder

Инициирует запрос к указанному эндпоинту. Возвращает билдер для выполнения запроса.

(cli *Client) Upgrade(hosts []string)

Атомарно обновить список хостов.

(cli *Client) Close() error

Закрыть соединение с сервером.

(cli *Client) BackendClient() isp.BackendServiceClient

Получить низкоуровневый клиент для прямого взаимодействия с gRPC-сервисом.

Functions

Default(restMiddlewares ...request.Middleware) (*Client, error)

Создать клиент с настройками по умолчанию:

  • Максимальный размер сообщения 64 МБ.
  • Middleware для генерации requestId, сбора метрик через grpc_metrics.ClientStorage и трейсинга
RequestId() request.Middleware

Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то передаваться будет именно он.

Log(logger log.Logger, logBody bool) request.Middleware

Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если logBody = true.

Metrics(storage MetricStorage) request.Middleware

Middleware для сбора метрик длительности запросов.

Usage

Default usage flow
package main

import (
	"context"
	"log"

	"github.com/txix-open/isp-kit/grpc/client"
	log2 "github.com/txix-open/isp-kit/log"
)

type user struct {
	Id   string
	Name string
}

func main() {
	logger, err := log2.New()
	if err != nil {
		log.Fatal(err)
	}

	cli, err := client.Default(client.Log(logger, true))
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()

	cli.Upgrade([]string{"host1:8080", "host2:9000"})

	users := make([]user, 0)
	err = cli.Invoke("/get_users").
		JsonResponseBody(&users).
		Do(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	for _, u := range users {
		/* handle each user */
	}
}

Documentation

Overview

Package client provides a gRPC client implementation with built-in load balancing, middleware support, and observability features.

The client supports dynamic host updates for service discovery and integrates with the ISP kit framework's logging, metrics, and tracing systems.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Log

func Log(logger log.Logger, logBody bool) request.Middleware

Log creates a middleware that logs gRPC client requests and responses. When logBody is true, request and response bodies are included in the logs. Logs at Debug level for requests and responses.

func LogWithOptions added in v1.66.3

func LogWithOptions(logger log.Logger, opts ...LogOption) request.Middleware

LogWithOptions creates a middleware that logs gRPC client requests and responses with custom options. Provides fine-grained control over what is logged (request body, response body, combined logs).

func Metrics

func Metrics(storage MetricStorage) request.Middleware

Metrics creates a middleware that collects timing metrics for gRPC client requests. The storage implementation receives the endpoint name and request duration.

func RequestId

func RequestId() request.Middleware

RequestId is a middleware that propagates request IDs across service boundaries. If no request ID is present in the context, it generates a new one. The request ID is added to outgoing metadata for tracing purposes.

Types

type Client

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

Client is a gRPC client with support for middleware, load balancing, and dynamic host updates. It provides a fluent API for building requests and automatically handles connection management. Client is safe for concurrent use by multiple goroutines.

func Default

func Default(restMiddlewares ...request.Middleware) (*Client, error)

Default creates a Client with pre-configured middleware for observability. Includes request ID propagation, metrics collection, and distributed tracing. Uses insecure transport by default (suitable for development and testing). Accepts additional middleware to be appended after the default ones. Returns an error if the client cannot be initialized.

func New

func New(initialHosts []string, opts ...Option) (*Client, error)

New creates a new Client with the specified initial hosts and options. Returns an error if the gRPC client cannot be initialized. The client automatically connects to the provided hosts and applies all configured middleware.

func (*Client) BackendClient

func (cli *Client) BackendClient() isp.BackendServiceClient

BackendClient returns the underlying gRPC BackendServiceClient. Useful for direct gRPC calls bypassing the client abstraction.

func (*Client) Close

func (cli *Client) Close() error

Close closes the gRPC client connection. Should be called when the client is no longer needed.

func (*Client) Invoke

func (cli *Client) Invoke(endpoint string) *request.Builder

Invoke creates a request builder for the specified endpoint. The builder provides a fluent API for configuring and executing the request.

func (*Client) Upgrade

func (cli *Client) Upgrade(hosts []string)

Upgrade updates the list of backend hosts for load balancing. This enables dynamic service discovery without restarting the client. Thread-safe for concurrent use.

type LogOption added in v1.66.3

type LogOption func(cfg *logConfig)

LogOption configures logging behavior for request middleware.

func WithCombinedLog added in v1.66.3

func WithCombinedLog(enable bool) LogOption

WithCombinedLog enables a single combined log entry for request and response. When disabled, requests and responses are logged separately.

func WithLogBody added in v1.66.3

func WithLogBody(logBody bool) LogOption

WithLogBody enables logging of both request and response bodies.

func WithLogRequestBody added in v1.66.3

func WithLogRequestBody(logRequestBody bool) LogOption

WithLogRequestBody enables or disables logging of request bodies.

func WithLogResponseBody added in v1.66.3

func WithLogResponseBody(logResponseBody bool) LogOption

WithLogResponseBody enables or disables logging of response bodies.

type MetricStorage

type MetricStorage interface {
	// ObserveDuration records the duration of a request for the given endpoint.
	ObserveDuration(endpoint string, duration time.Duration)
}

MetricStorage defines the interface for metric storage implementations. Used by the Metrics middleware to collect timing information.

type Option

type Option func(cli *Client)

Option configures a Client using the functional options pattern.

func WithDialOptions

func WithDialOptions(dialOptions ...grpc.DialOption) Option

WithDialOptions sets custom gRPC dial options for the client. Note: This replaces any previously set dial options.

func WithMiddlewares

func WithMiddlewares(middlewares ...request.Middleware) Option

WithMiddlewares adds one or more request middleware to the client. Middleware are executed in the order they are provided.

Directories

Path Synopsis
Package request provides a fluent builder for constructing and executing gRPC requests.
Package request provides a fluent builder for constructing and executing gRPC requests.

Jump to

Keyboard shortcuts

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