dim

package
v0.3.0 Latest Latest
Warning

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

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

Documentation

Overview

Package dim is a slim, generics-based dependency-injection toolkit: lazy providers and managed resources built from plain functions, with structured logging of initialization and cleanup. It mirrors the lavka-promoaction pkg/dim design so applications can adopt the same wiring style.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewResource

func NewResource[T any](name string, factory func(context.Context) (T, CleanupFunc, error)) (Provider[T], CleanupFunc)

NewResource creates a new managed resource and returns Provider and CleanupFunc. factory must return: (resource, cleanup_function, error).

Usage:

c.Store, cleanup := dim.NewResource("Store", func(ctx context.Context) (store.Store, dim.CleanupFunc, error) {
    st := postgres.New(c.Logger)
    if err := st.Connect(config); err != nil {
        return nil, nil, err
    }
    return st, func() error { return st.Close() }, nil
})
return cleanup, nil

Note: Go cannot infer T from the named type FactoryFunc[T], so the signature takes an anonymous function literal.

Types

type CleanupFunc

type CleanupFunc func() error

CleanupFunc - function to close/clean up a resource. Functions are added in initialization order and are called in reverse order (LIFO).

func NamedCleanup

func NamedCleanup(name string, fn func() error) CleanupFunc

NamedCleanup creates a function with closure on name that logs the resource name and execution time.

type FactoryFunc

type FactoryFunc[T any] func(ctx context.Context) (T, CleanupFunc, error)

FactoryFunc is a function that creates a resource and returns it along with an optional cleanup function.

type Provider

type Provider[T any] func(ctx context.Context) T

Provider is a function that returns a resource value.

func Once

func Once[T any](factory func(ctx context.Context) (T, error)) Provider[T]

Once wraps factory in a Provider that runs it a single time, caching the result. A factory error is fatal and panics — initialization failures should surface at startup, not be silently swallowed at call sites.

func OnceWithName

func OnceWithName[T any](name string, factory func(ctx context.Context) (T, error)) Provider[T]

OnceWithName creates a Provider with logging by dependency name.

Jump to

Keyboard shortcuts

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