app

package
v1.67.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 4 Imported by: 3

README

Package app

Пакет app предназначен для создания приложений с простым и гибким управлением жизненным циклом.

Types

Application

Структура Application представляет собой абстракцию, которая содержит в себе основные необходимые компоненты приложения (logger, config, context), а также позволяет простым и гибким способом управлять жизненным циклом компонент приложения реализующих интерфейсы Runner и Closer.

Methods:

(a *Application) Context() context.Context

Получить контекст приложения.

(a *Application) Config() *config.Config

Получить конфигурацию приложения.

(a *Application) Logger() *log.Adapter

Получить логгер.

(a *Application) AddRunners(runners ...Runner)

Добавить компоненты приложения, реализующих интерфейс Runner.

(a *Application) AddClosers(closers ...Closer)

Добавить компоненты приложения, реализующих интерфейс Closer.

(a *Application) Run() error

Вызывает у каждой Runner компоненты приложения метод Run. Блокирующая операция. Если хотя бы одна компонента при запуске вернула ошибку, то метод Run завершается с ошибкой.

(a *Application) Close()

Вызывает у каждой Closer компоненты приложения метод Close.

(a *Application) Shutdown()

То же самое, что и метод Close, но в конце дополнительно завершает контекст.

Usage

Default usage flow
package main

import (
	"context"
	"log"

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

func noopRunnerFn(_ context.Context) error { return nil }

func noopCloserFn() error { return nil }

type noopRunner struct{}

func (r noopRunner) Run(_ context.Context) error { return nil }

type noopCloser struct{}

func (c noopCloser) Close() error { return nil }

func main() {
	application, err := app.New()
	if err != nil {
		log.Fatal(err)
	}
	application.AddRunners(app.RunnerFunc(noopRunnerFn), noopRunner{})
	application.AddClosers(app.CloserFunc(noopCloserFn), noopCloser{})

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

	err = application.Run() /* blocking here */
	if err != nil {
		log.Fatal(err)
	}
}

Construct Application instance with options
package main

import (
	"log"

	"github.com/txix-open/isp-kit/app"
	"github.com/txix-open/isp-kit/config"
	log2 "github.com/txix-open/isp-kit/log"
	"github.com/txix-open/isp-kit/validator"
)

func main() {
	application, err := app.New(
		app.WithConfigOptions(
			config.WithValidator(validator.Default),
			/* pass the config options you want */
		),
		app.WithLoggerConfigSupplier(func(cfg *config.Config) log2.Config {
			var loggerCfg log2.Config
			/* form the logger config the way you want */
			return loggerCfg
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	...
}

Construct Application instance with config
package main

import (
	"log"

	"github.com/txix-open/isp-kit/app"
	"github.com/txix-open/isp-kit/config"
	"github.com/txix-open/isp-kit/validator"
)

func main() {
	config := app.Config{
		ConfigOptions: []config.Option{
			config.WithValidator(validator.Default),
			/* pass the config options you want */
		},
	}
	application, err := app.NewFromConfig(config)
	if err != nil {
		log.Fatal(err)
	}
	...
}

Documentation

Overview

Package app provides a lightweight application lifecycle management framework.

The Application struct orchestrates the startup and shutdown of multiple Runner components, handling graceful lifecycle transitions and resource cleanup.

Usage

Create a new application with optional configuration:

app, err := app.New(
	app.WithConfigOptions(config.WithExtraSource(config.NewYamlConfig("config.yaml"))),
	app.WithLoggerConfigSupplier(func(cfg *config.Config) log.Config {
		return *log.DefaultConfig()
	}),
)
if err != nil {
	log.Fatal(err)
}

Add runners and closers:

app.AddRunners(myRunner)
app.AddClosers(myCloser)

Start the application:

if err := app.Run(); err != nil {
	log.Fatal(err)
}

Shutdown when needed:

app.Shutdown()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Application

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

Application manages the lifecycle of long-running services. It coordinates the startup and graceful shutdown of multiple Runner components, providing context propagation and resource cleanup through Closers.

Application is not safe for concurrent modification. All AddRunners and AddClosers calls should be made before calling Run.

func New

func New(opts ...Option) (*Application, error)

New creates a new Application instance with the provided options. It applies the options to a DefaultConfig and then creates the application from the resulting configuration.

Returns an error if the configuration or logger cannot be initialized.

func NewFromConfig

func NewFromConfig(appConfig Config) (*Application, error)

NewFromConfig creates a new Application from the provided configuration. It initializes the configuration, logger, and context, setting up the application with a default closer that syncs the logger on shutdown.

Returns an error if the configuration or logger cannot be initialized.

func (*Application) AddClosers

func (a *Application) AddClosers(closers ...Closer)

AddClosers appends the provided closers to the application. Closers are invoked during shutdown to release resources.

AddClosers should be called before Run to ensure proper cleanup.

func (*Application) AddRunners

func (a *Application) AddRunners(runners ...Runner)

AddRunners appends the provided runners to the application. Runners are started as goroutines when Run is called.

AddRunners should be called before Run to ensure proper initialization.

func (*Application) Close

func (a *Application) Close()

Close invokes all registered closers to release resources. Errors from individual closers are logged but do not halt the shutdown process.

func (*Application) Config

func (a *Application) Config() *config.Config

Config returns the application's configuration.

func (*Application) Context

func (a *Application) Context() context.Context

Context returns the application's context. The context is cancelled when Shutdown is called.

func (*Application) Logger

func (a *Application) Logger() *log.Adapter

Logger returns the application's logger.

func (*Application) Run

func (a *Application) Run() error

Run starts all registered runners and blocks until one of them returns an error or the application context is cancelled.

Each runner executes in its own goroutine. If any runner fails, Run returns the first error encountered. If the context is cancelled via Shutdown, Run returns nil.

Run is safe to call only once per Application instance.

func (*Application) Shutdown

func (a *Application) Shutdown()

Shutdown initiates graceful shutdown by closing all resources and cancelling the application context.

Shutdown should be called to terminate running services and release resources.

type Closer

type Closer interface {
	Close() error
}

Closer represents a resource that needs to be cleaned up. Implementations should release resources and return an error if cleanup fails.

type CloserFunc

type CloserFunc func() error

CloserFunc is a function adapter that implements the Closer interface. It allows using simple functions as closers without defining a new type.

Example usage:

closer := app.CloserFunc(func() error {
	// close database connection
	return nil
})

func (CloserFunc) Close

func (c CloserFunc) Close() error

Close executes the underlying function to release resources.

type Config

type Config struct {
	// LoggerConfigSupplier generates the logger configuration from app config.
	LoggerConfigSupplier LoggerConfigSupplier
	// ConfigOptions are passed to the underlying configuration system.
	ConfigOptions []config.Option
}

Config holds the configuration for creating an Application.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a new Config with sensible defaults. The default logger configuration supplier returns a standard log.Config.

type LoggerConfigSupplier

type LoggerConfigSupplier func(cfg *config.Config) log.Config

LoggerConfigSupplier is a function that generates a logger configuration based on the application configuration.

type Option

type Option func(c *Config)

Option is a function that configures an Application configuration. Options follow the functional options pattern for flexible configuration.

func WithConfigOptions

func WithConfigOptions(opts ...config.Option) Option

WithConfigOptions creates an Option that appends configuration options to the Application's config.

Example:

app, err := app.New(
	app.WithConfigOptions(
		config.WithExtraSource(config.NewYamlConfig("config.yaml")),
		config.WithEnvPrefix("APP"),
	),
)

func WithLoggerConfigSupplier

func WithLoggerConfigSupplier(supplier LoggerConfigSupplier) Option

WithLoggerConfigSupplier creates an Option that sets the logger configuration supplier function.

Example:

app, err := app.New(
	app.WithLoggerConfigSupplier(func(cfg *config.Config) log.Config {
		logCfg := *log.DefaultConfig()
		logCfg.Level = log.DebugLevel
		return logCfg
	}),
)

type Runner

type Runner interface {
	Run(ctx context.Context) error
}

Runner represents a long-running service or task. Implementations should block while running and return an error on failure. The context is cancelled when the application shuts down.

type RunnerFunc

type RunnerFunc func(ctx context.Context) error

RunnerFunc is a function adapter that implements the Runner interface. It allows using simple functions as runners without defining a new type.

Example usage:

run := app.RunnerFunc(func(ctx context.Context) error {
	for {
		select {
		case <-ctx.Done():
			return nil
		// process work
		}
	}
})

func (RunnerFunc) Run

func (r RunnerFunc) Run(ctx context.Context) error

Run executes the underlying function with the provided context.

Jump to

Keyboard shortcuts

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