cog

package module
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2024 License: MIT Imports: 9 Imported by: 0

README

cog

Config tool for Go applications that require configuration changes on-the-fly.

go get github.com/leonidasdeim/cog

Overview

Currently cog supports JSON, YAML and TOML configuration files with built-in handler/filehandler.go. By default it dynamically detects configuration file type. If you want to specify file type, here you can find how to use built-in file handlers. You can always write your own handler which would implement ConfigHandler interface.

Default config with initial configuration information should be placed in root folder named <name>.default.<type>. Name and type of the file could be changed using custom parameters. cog also let to you set up default values for entries in configuration with default:"some_value" tag. Right now, only bool, int and string is supported.

It is possible to load config fields values from environment variables using env:"ENV_VAR_NAME" tag. With this tag cog will take env. variable value and use it if field value not provided in the config file.

cog uses validator library for validating loaded configuration. For example you can specify required configuration items with validate:"required" tag.

Getting started

Write config structure of your app. Example of config structure with different tags:

type Config struct {
    // simple field, will be empty string if not provided
    Name      string 

    // required: will fail if not provided
    Version   string `validate:"required"` 
    
    // tries to load from env. variable "SERVER_IP_ADDRESS" if not provided in the config file
    Address   string `validate:"required,ip" env:"SERVER_IP_ADDRESS"` 
    
    // sets default value "8080" if field not provided in the config file
    Port      string `default:"8080"` 
}

Import main library:

import "github.com/leonidasdeim/cog"

Initialize and use config:

// creates default cog instance with JSON file handler
c, err := cog.Init[Config]()

// access current configuration attributes
config := c.Config()

// make some changes to 'config' and update current configuration
c.UpdateConfig(newConfig)

For more examples check out examples/ folder.

Change notifications

Callbacks

Register a callback function, which will be called on config change in non blocking way:

id := c.AddCallback(func(cfg ConfigType) {
    // handle config update
})

Callback could be removed by id:

c.RemoveCallback(id)
Subscribers

You can register another type of callback - subscriber. It will be called on config change and will wait for it to complete. It has different signature than callback: it can return an error and in case subscriber callback returns an error - whole config update is being rolled back. Example:

id := c.AddSubscriber(func(cfg ConfigType) error {
    if err := tryConfigUpdate(cfg); err != nil {
        return err
    }
    return nil
})

Subscriber could be removed dynamically:

c.RemoveSubscriber(id)

File handler

By default cog initializes with dynamic file handler. You can specify type (JSON, YAML or TOML) by creating handler instance and providing it during initialization.

Import built-in filehandler

import (
	"github.com/leonidasdeim/cog"
	fh "github.com/leonidasdeim/cog/filehandler"
)
h, _ := fh.New(fh.WithType(fh.YAML))
c, _ := cog.Init[ConfigType](h)
Custom parameters

Handlers also support optional parameters with high order functions. You can specify custom path, name and file handler.

h, _ := fh.New(
    fh.WithPath("./dir"), 
    fh.WithName("name"), 
    fh.WithType(fh.JSON),
)
c, _ := cog.Init[ConfigType](h)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetDefaults added in v1.7.0

func SetDefaults[T any](data *T)

Types

type C added in v1.7.0

type C[T any] struct {
	// contains filtered or unexported fields
}

func Init

func Init[T any](handler ...ConfigHandler) (*C[T], error)

Initialize library. Returns cog instance. Receives config handler. To use default builtin JSON file handler: c, err := cog.Init[ConfigStruct](handler.New())

func (*C[T]) AddCallback added in v1.7.0

func (cog *C[T]) AddCallback(f Callback[T]) int

Register new callback function. It will be called after config update in non blocking goroutine. This method returns callback id (int). It can be used to remove callback by calling cog.RemoveCallback(id).

func (*C[T]) AddSubscriber added in v1.7.0

func (cog *C[T]) AddSubscriber(f Subscriber[T]) int

Register new subscriber function. It will be called after config update and wait for every subscriber to be updated. If at least one subscriber returns an error, update stops and rollback is initiated for all updated subscribers. This method returns subscriber id (int). It can be used to remove subscriber by calling cog.RemoveSubscriber(id).

func (*C[T]) Config added in v1.7.0

func (cog *C[T]) Config() T

Get configuration data.

func (*C[T]) GetTimestamp added in v1.7.0

func (cog *C[T]) GetTimestamp() string

Get timestamp of the configuration. It reflects when configuration has been updated or loaded last time.

func (*C[T]) RemoveCallback added in v1.7.0

func (cog *C[T]) RemoveCallback(id int) error

Remove callback by id.

func (*C[T]) RemoveSubscriber added in v1.7.0

func (cog *C[T]) RemoveSubscriber(id int) error

Remove subscriber by id.

func (*C[T]) String added in v1.8.0

func (cog *C[T]) String(masks ...MaskFn[T]) (string, error)

func (*C[T]) Update added in v1.7.0

func (cog *C[T]) Update(new T) error

Update configuration data. After update subscribers will be notified.

type Callback

type Callback[T any] func(T)

type ConfigHandler

type ConfigHandler interface {
	Load(any) error
	Save(any) error
}

type MaskFn added in v1.8.0

type MaskFn[T any] func(*T)

type Subscriber added in v1.7.0

type Subscriber[T any] func(T) error

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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