grpc_client

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 10 Imported by: 0

README

Compogo gRPC Client 🔌

Compogo gRPC Client — это легковесный gRPC-клиент для внутреннего взаимодействия сервисов. Спроектирован для работы в доверенных сетях (например, внутри Kubernetes) и не включает поддержку TLS — это зона ответственности инфраструктуры (service mesh) или отдельных компонентов.

🚀 Установка

go get github.com/Compogo/grpc-client
📦 Быстрый старт
package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/grpc-client"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        grpc_client.Component,  // добавляем gRPC-клиент
        compogo.WithComponents(
            userServiceComponent,
        ),
    )

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

// Компонент, использующий gRPC-клиент
var userServiceComponent = &component.Component{
    Dependencies: component.Components{grpc_client.Component},
    Execute: component.StepFunc(func(c container.Container) error {
        return c.Invoke(func(client *grpc_client.Client) {
            // клиент уже готов к работе
            service := &UserService{client: client}
            service.Register()
        })
    }),
}

type UserService struct {
    client *grpc_client.Client
}

func (s *UserService) GetUser(ctx context.Context, id int) (*User, error) {
    req := &pb.GetUserRequest{Id: id}
    var resp pb.GetUserResponse
    err := s.client.Invoke(ctx, "/users.UserService/Get", req, &resp)
    // ...
}
✨ Возможности
🎯 Простая конфигурация через флаги
./myapp \
    --client.grpc.address=users-service \
    --client.grpc.port=9090 \
    --client.grpc.keepalive.time=10s \
    --client.grpc.keepalive.timeout=20s \
    --client.grpc.permit_without_stream=true
🔒 Безопасность

Данный компонент не поддерживает TLS — он предназначен для использования в доверенных сетях (например, внутри Kubernetes). Если требуется шифрование трафика:

  • Используйте service mesh (istio, linkerd) — они добавят mTLS прозрачно
  • Оберните клиент в свой компонент с grpc.WithTransportCredentials
  • Терминируйте TLS на входе в кластер (внешние клиенты)

Documentation

Index

Constants

View Source
const (
	PermitWithoutStreamFieldName = "client.grpc.permit_without_stream"
	KeepaliveTimeFieldName       = "client.grpc.keepalive.time"
	KeepaliveTimeoutFieldName    = "client.grpc.keepalive.timeout"
	AddressFieldName             = "client.grpc.address"
	PortFieldName                = "client.grpc.port"

	PermitWithoutStreamDefault = true
	KeepaliveTimeDefault       = time.Second * 10
	KeepaliveTimeoutDefault    = time.Second * 20
	AddressDefault             = "127.0.0.1"
	PortDefault                = uint16(9090)
)

Variables

View Source
var Component = &component.Component{
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewClient,
			func(client *Client) grpc.ClientConnInterface { return client },
		)
	}),
	BindFlags: component.BindFlags(func(flagSet flag.FlagSet, container container.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: component.StepFunc(func(container container.Container) error {
		return container.Invoke(Configuration)
	}),
	Stop: component.StepFunc(func(container container.Container) error {
		return container.Invoke(func(client *Client) error {
			return client.Close()
		})
	}),
}

Component is a ready-to-use Compogo component that provides a gRPC client. It automatically:

  • Registers Config and Client in the DI container
  • Adds command-line flags for client configuration
  • Configures the client during Configuration phase
  • Closes the connection during Stop phase

Usage:

compogo.WithComponents(
    grpc_client.Component,
    // ... your service components that need gRPC client
)

Then in your service component:

type UserService struct {
    client *grpc_client.Client
}

func (s *UserService) GetUser(ctx context.Context, id int) (*User, error) {
    var resp pb.GetUserResponse
    err := s.client.Invoke(ctx, "/users.UserService/Get", &req, &resp)
    // ...
}

Functions

This section is empty.

Types

type Client

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

Client wraps a gRPC client connection with Compogo lifecycle support. It provides a simplified interface for making RPC calls and handles connection lifecycle (creation, keepalive, cleanup).

func NewClient

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

NewClient creates a new gRPC client connection with the given configuration. It sets up:

  • Connection target (address:port)
  • Keepalive parameters (ping interval, timeout, behavior)
  • Insecure credentials (for trusted networks only)

For TLS support, wrap this component or use a service mesh.

func (*Client) Close

func (client *Client) Close() error

func (*Client) Invoke

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

func (*Client) NewStream

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

type Config

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

func Configuration

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

Configuration applies configuration values to the Config struct. It reads from the provided configurator and sets defaults if values are not present. This function is designed to be used with container.Invoke in the Configuration phase.

func NewConfig

func NewConfig() *Config

Jump to

Keyboard shortcuts

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