Help us shape the future of Go! Take the 2026 Go Developer Survey

request

package
v1.75.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 8 Imported by: 0

README

Package request

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

Types

Builder

Структура для пошагового конструирования gRPC-запроса. Обрабатывает сериализацию/десериализацию JSON, управление контекстом и метаданными.

Methods:

NewBuilder(roundTripper RoundTripper, endpoint string) *Builder

Создать новый билдер для указанного эндпоинта.

(req *Builder) ApplicationId(appId int) *Builder

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

(req *Builder) JsonRequestBody(reqBody any) *Builder

Задать тело запроса в формате JSON. Объект будет сериализован автоматически при помощи функций из пакета json (маршалинг без тэгов в camelCase).

(req *Builder) JsonResponseBody(respPtr any) *Builder

Задать указатель для десериализации тела ответа из JSON.

(req *Builder) Timeout(timeout time.Duration) *Builder

Установить тайм-аут для запроса. По умолчанию: 15 секунд.

(req *Builder) AppendMetadata(k string, v ...string) *Builder

Добавить кастомные метаданные в запрос.

(b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder

Установить флаг кодирования запроса. Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен content-encoding со значением типа codec и тело запроса будет закодировано.

(b *RequestBuilder) EncodeThreshold(threshold int) *RequestBuilder

Установить threshold в байтах, выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest).

(b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder

Установить флаг приёма закодированных ответов. Если включен, то в заголовки запроса будет добавлен accept-encoding со значением типа codec + identity (пример zstd, identity).

(req *Builder) Do(ctx context.Context) error

Выполнить запрос. Автоматически:

  1. Сериализует тело запроса в JSON
  2. Добавляет системные заголовки (x-application-identity, proxy_method_name)
  3. Обрабатывает цепочку middleware
  4. Десериализует ответ (если задан responsePtr)

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"
	"time"

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

type getUserRequest struct {
	Id string
}

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"})

	u := new(user)
	err = cli.Invoke("/get_user").
		ApplicationId(88).
		JsonRequestBody(getUserRequest{Id: "some-user-id"}).
		JsonResponseBody(u).
		Timeout(5 * time.Second).
		Do(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	
	log.Printf("username: %s\n", u.Name)
}

Documentation

Overview

Package request provides a fluent builder for constructing and executing gRPC requests. It handles JSON marshaling/unmarshaling, metadata management, and timeout configuration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder struct {
	Endpoint       string
	MD             metadata.MD
	EncodeSettings EncodeSettings
	// contains filtered or unexported fields
}

Builder provides a fluent API for constructing and executing gRPC requests. It handles JSON marshaling, metadata management, and timeout configuration. Builder is not safe for concurrent use; create a new instance for each request.

func NewBuilder

func NewBuilder(
	roundTripper RoundTripper,
	endpoint string,
	encodeSettings EncodeSettings,
) *Builder

NewBuilder creates a new Builder for the specified endpoint. Initializes with default timeout and empty metadata.

func (*Builder) AcceptEncodedResponse added in v1.71.0

func (b *Builder) AcceptEncodedResponse(accept bool) *Builder

AcceptEncodedResponse enables transparent handling of encoded GRPC responses.

When enabled, the client adds "accept-encoding" (e.g. zstd) to request headers, allowing the server to return encoded payloads.

func (*Builder) AppendMetadata

func (req *Builder) AppendMetadata(k string, v ...string) *Builder

AppendMetadata adds one or more values to the metadata key. Returns the Builder for method chaining.

func (*Builder) ApplicationId

func (req *Builder) ApplicationId(appId int) *Builder

ApplicationId sets the application identity header for the request. Returns the Builder for method chaining.

func (*Builder) Do

func (req *Builder) Do(ctx context.Context) error

Do executes the request and unmarshals the response if a response pointer was provided. Returns an error if JSON marshaling, request execution, or response unmarshaling fails. Automatically applies the configured timeout to the request context.

func (*Builder) EncodeRequest added in v1.71.0

func (b *Builder) EncodeRequest(encode bool) *Builder

EncodeRequest sets encoding for request body. It affects content-encoding and request body serialization.

func (*Builder) EncodeThreshold added in v1.71.0

func (b *Builder) EncodeThreshold(thresholdBytes int) *Builder

EncodeThreshold sets the request encoding threshold in bytes.

func (*Builder) JsonRequestBody

func (req *Builder) JsonRequestBody(reqBody any) *Builder

JsonRequestBody sets the request body as a JSON-encodable value. Returns the Builder for method chaining.

func (*Builder) JsonResponseBody

func (req *Builder) JsonResponseBody(respPtr any) *Builder

JsonResponseBody sets the pointer to unmarshal the JSON response into. Returns the Builder for method chaining.

func (*Builder) Timeout

func (req *Builder) Timeout(timeout time.Duration) *Builder

Timeout sets the request timeout duration. A timeout of zero or negative disables the timeout. Returns the Builder for method chaining.

type EncodeSettings added in v1.71.0

type EncodeSettings struct {
	EncodeRequest         bool
	EncodeThreshold       int
	AcceptEncodedResponse bool
}

type Middleware

type Middleware func(next RoundTripper) RoundTripper

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

type RoundTripper

type RoundTripper func(ctx context.Context, builder *Builder, message *isp.Message) (*isp.Message, error)

RoundTripper defines the interface for executing gRPC requests. Receives a context, request builder, and message; returns a response message and optional error. Used as the base for middleware chains.

Jump to

Keyboard shortcuts

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