startup

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

README

startup

Contains startup related structs, helpers, and can be used to handle the startup and shutdown of a service.

Install

go get github.com/blutspende/libs-startup

Startup

It is a fully configurable drop-in replacement for most of the boilerplate code in the main() function. It handles .env and configuration reading, database connection, initializations, and graceful shutdown.

It can be configured using the startup.Config struct, and used with the startup.Startup(cfg) method. The configuration allows for granular selection of initialized components and optional injection of custom initialization and shutdown functions.

Property Description
Configuration An instance of a Configuration interface (required)
ApplicationName Required to be set to a non-empty value
BuildVersion Recommended to be set if OTEL and/or Pyroscope is used
UsePostgres Enables the setup and connection to a postgres database
UseExtendedPgConfig Turns on the use of advanced connection configurations options
UseRedis Enables the setup of a Redis client
UseOtel Enables the use of OpenTelemetry
UsePyroscope Enables the use of Pyroscope
UtcLogging Sets log times to UTC as opposed to local time
StartupExtensionFunc Custom function injected into the startup process (can be nil)
ShutdownExtensionFunc Custom function injected into the shutdown process (can be nil)

Config

Contains a base CommonConfiguration struct that can be embedded in other configuration structs to provide common configuration values, and a ReadConfiguration function to read environment variables and do basic common processing.

It also contains a Configuration interface that should be implemented by any service specific configuration struct to be usable in ReadConfiguration and in various things from this library.

Here is an example of a service specific configuration struct:

import startup "github.com/blutspende/libs-startup"

type Configuration struct {
    startup.CommonConfiguration
	
    ServiceSpecific string `envconfig:"SERVICE_SPECIFIC" required:"true"`
}

func (c *Configuration) GetCommonConfig() *startup.CommonConfiguration {
    return &c.CommonConfiguration
}

Documentation

Index

Constants

View Source
const ContextKeyCorrelation = "correlation_id"

Variables

View Source
var ErrApplicationNameMissing = errors.New("ApplicationName is required in the startup configuration")
View Source
var ErrFailedToLoadDotEnvFile = errors.New("failed to load .env file")
View Source
var ErrFailedToParseLogLevel = errors.New("failed to parse log level")
View Source
var ErrFailedToReadConfiguration = errors.New("failed to read configuration")
View Source
var ErrInvalidLogLevel = errors.New("invalid log level")

Functions

func ReadConfiguration

func ReadConfiguration(configuration Configuration) error

func Startup

func Startup(cfg Config) (ctx context.Context, dbConn db.DbConnection,
	redisClient *redis.Client)

Types

type CommonConfiguration

type CommonConfiguration struct {
	ApplicationName string
	BuildVersion    string

	LogLevel     string `envconfig:"LOG_LEVEL" default:"INFO"`
	ZeroLogLevel zerolog.Level

	PostgresDB struct {
		Host               string `envconfig:"DB_SERVER" required:"true"`
		Port               uint32 `envconfig:"DB_PORT" required:"true"`
		User               string `envconfig:"DB_USER" required:"true"`
		Pass               string `envconfig:"DB_PASS" required:"true"`
		Database           string `envconfig:"DB_DATABASE" required:"true"`
		SSLMode            string `envconfig:"DB_SSL_MODE" required:"true"`
		EnableQueryLogging bool   `envconfig:"DB_QUERY_LOGGING" default:"false"`
		// Extended settings
		MaxOpenConnections           int `envconfig:"DB_MAX_OPEN_CONNECTIONS" default:"8"`
		MaxIdleConnections           int `envconfig:"DB_MAX_IDLE_CONNECTIONS" default:"8"`
		ConnectionMaxLifetimeSeconds int `envconfig:"DB_CONNECTION_MAX_LIFETIME_SECONDS" default:"180"`
		ConnectionMaxIdleTimeSeconds int `envconfig:"DB_CONNECTION_MAX_IDLE_TIME_SECONDS" default:"30"`
	}

	OIDC struct {
		BaseURL      string `envconfig:"OIDC_BASE_URL" required:"false"`
		ClientID     string `envconfig:"OIDC_CLIENT_ID" required:"false"`
		ClientSecret string `envconfig:"OIDC_CLIENT_SECRET" required:"false"`
	}

	Redis struct {
		Enable                   bool   `envconfig:"REDIS_ENABLE" default:"false"`
		Address                  string `envconfig:"REDIS_ADDRESS" default:"redis:6379"`
		Password                 string `envconfig:"REDIS_PASSWORD" default:""`
		DefaultTTLMinutes        int    `envconfig:"REDIS_DEFAULT_TTL_MINUTES" default:"1440"`
		RefreshRetryAttempts     int    `envconfig:"REDIS_REFRESH_RETRY_ATTEMPTS" default:"5"`
		RefreshRetryWaitStartMs  int    `envconfig:"REDIS_REFRESH_RETRY_WAIT_START_MS" default:"500"`
		RefreshRetryWaitExponent int    `envconfig:"REDIS_REFRESH_RETRY_WAIT_EXPONENT" default:"5"`
		MaxRetries               int    `envconfig:"REDIS_MAX_RETRIES" default:"-1"`
		DialerRetries            int    `envconfig:"REDIS_DIALER_RETRIES" default:"1"`
		DialerRetryTimeoutMs     int    `envconfig:"REDIS_DIALER_RETRY_TIMEOUT_MS" default:"50"`
	}

	OpenTelemetry struct {
		Enable                       bool   `envconfig:"OTEL_ENABLE" default:"false"`
		TraceCollectorEndpoint       string `envconfig:"OTEL_TRACE_COLLECTOR_ENDPOINT" default:"otel:4317"`
		TraceCollectorTimeoutSeconds int    `envconfig:"OTEL_TRACE_COLLECTOR_TIMEOUT_SECONDS" default:"5"`
		MetricsCollectorEndpoint     string `envconfig:"OTEL_METRICS_COLLECTOR_ENDPOINT" required:"false" default:"otel:4317"`
		MetricsReaderTimeoutSeconds  int    `envconfig:"OTEL_METRICS_READER_TIMEOUT_SECONDS" default:"5"`
		MetricsReaderIntervalSeconds int    `envconfig:"OTEL_METRICS_READER_INTERVAL_SECONDS" default:"15"`
		ReadMemStatsIntervalSeconds  int    `envconfig:"OTEL_READ_MEMSTATS_INTERVAL_SECONDS" default:"30"`
	}

	Pyroscope struct {
		Enable bool   `envconfig:"PYROSCOPE_ENABLE" default:"false"`
		Server string `envconfig:"PYROSCOPE_SERVER" default:"http://pyroscope:4040"`
	}
}

func (*CommonConfiguration) GetCommonConfig

func (c *CommonConfiguration) GetCommonConfig() *CommonConfiguration

type Config

type Config struct {
	Configuration         Configuration
	ApplicationName       string
	BuildVersion          string
	UsePostgres           bool
	UseExtendedPgConfig   bool
	UseRedis              bool
	UseOtel               bool
	UsePyroscope          bool
	UtcLogging            bool
	StartupExtensionFunc  func(Configuration) error
	ShutdownExtensionFunc func()
}

type Configuration

type Configuration interface {
	GetCommonConfig() *CommonConfiguration
}

Jump to

Keyboard shortcuts

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