grpc_client

package module
v1.0.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 8 Imported by: 0

README

Compogo gRPC Client

Go Reference

GRPC-клиент для фреймворка Compogo.

Предоставляет:

  • GRPC-клиент с настройками keepalive
  • Интеграцию с Compogo через компонент
  • Закрытие соединения при завершении приложения

Установка

go get github.com/Compogo/grpc_client

Быстрый старт

package main

import (
    "context"

    "github.com/Compogo/compogo"
    "github.com/Compogo/grpc_client"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithComponents(&grpc_client.Component),
    )

    app.AddComponents(&compogo.Component{
        Name: "my_service",
        Init: compogo.StepFunc(func(container compogo.Container) error {
            return container.Invoke(func(client *grpc_client.Client) error {
                // Использование клиента
                var response MyResponse
                err := client.Invoke(context.Background(), "/MyService/Get", &MyRequest{}, &response)
                return err
            })
        }),
    })

    if err := app.Serve(); err != nil {
        panic(err)
    }
}

Конфигурация

Флаги командной строки
# Адрес сервера
--client.grpc.address=127.0.0.1

# Порт сервера
--client.grpc.port=9090

# Keepalive настройки
--client.grpc.keepalive.time=10s
--client.grpc.keepalive.timeout=20s
--client.grpc.permit_without_stream=true

Зависимости

Лицензия

MIT License

Copyright (c) 2026 Compogo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

View Source
const (
	// PermitWithoutStreamFieldName разрешать keepalive без стримов
	PermitWithoutStreamFieldName = "client.grpc.permit_without_stream"

	// KeepaliveTimeFieldName интервал keepalive пингов
	KeepaliveTimeFieldName = "client.grpc.keepalive.time"

	// KeepaliveTimeoutFieldName таймаут keepalive
	KeepaliveTimeoutFieldName = "client.grpc.keepalive.timeout"

	// AddressFieldName адрес сервера
	AddressFieldName = "client.grpc.address"

	// PortFieldName порт сервера
	PortFieldName = "client.grpc.port"
)

Variables

View Source
var (
	PermitWithoutStreamDefault = true
	KeepaliveTimeDefault       = time.Second * 10
	KeepaliveTimeoutDefault    = time.Second * 20
	AddressDefault             = "127.0.0.1"
	PortDefault                = uint16(9090)
)
View Source
var Component = compogo.Component{
	Init: compogo.StepFunc(func(container compogo.Container) error {
		return container.Provides(
			NewConfig,
			NewClient,
			func(client *Client) grpc.ClientConnInterface { return client },
		)
	}),
	BindFlags: compogo.BindFlags(func(flagSet flag.FlagSet, container compogo.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.StringVar(&config.Address, AddressFieldName, AddressDefault, "")
			flagSet.Uint16Var(&config.Port, PortFieldName, PortDefault, "")
			flagSet.BoolVar(&config.PermitWithoutStream, PermitWithoutStreamFieldName, PermitWithoutStreamDefault, "")
			flagSet.DurationVar(&config.KeepaliveTime, KeepaliveTimeFieldName, KeepaliveTimeDefault, "")
			flagSet.DurationVar(&config.KeepaliveTimeout, KeepaliveTimeoutFieldName, KeepaliveTimeoutDefault, "")
		})
	}),
	Configuration: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(Configuration)
	}),
	Stop: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(func(client *Client) error {
			return client.Close()
		})
	}),
}

Component — компонент GRPC-клиента для Compogo. Регистрирует клиент в DI-контейнере.

Пример:

app.AddComponents(&grpc_client.Component)

var client *grpc_client.Client
container.Invoke(func(c *grpc_client.Client) { client = c })

// Использование как grpc.ClientConnInterface
response, err := client.Invoke(ctx, "/MyService/Get", &Request{}, &Response{})

Functions

This section is empty.

Types

type Client

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

Client представляет GRPC-клиент с поддержкой keepalive. Реализует интерфейс grpc.ClientConnInterface.

func NewClient

func NewClient(config *Config) (*Client, error)

NewClient создаёт новый GRPC-клиент. Настраивает keepalive параметры и insecure соединение.

func (*Client) Close

func (client *Client) Close() error

Close закрывает GRPC-соединение.

func (*Client) Invoke

func (client *Client) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error

Invoke вызывает RPC метод. Реализует интерфейс grpc.ClientConnInterface.

func (*Client) NewStream

func (client *Client) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption) (grpc.ClientStream, error)

NewStream создаёт новый стрим. Реализует интерфейс grpc.ClientConnInterface.

type Config

type Config struct {
	PermitWithoutStream bool
	Port                uint16
	Address             string
	KeepaliveTime       time.Duration
	KeepaliveTimeout    time.Duration
}

Config содержит конфигурацию GRPC-клиента.

func Configuration

func Configuration(config *Config, configurator compogo.Configurator) *Config

Configuration загружает конфигурацию из Configurator.

func NewConfig

func NewConfig() *Config

NewConfig создаёт новую конфигурацию.

Jump to

Keyboard shortcuts

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