chu

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2025 License: MIT Imports: 15 Imported by: 2

README

chu

License Coverage GitHub Workflow Status Go Report Card Go PKG

Configuration library to load from multiple sources.

go get github.com/rakunlabs/chu

Usage

Define a struct to hold the configuration.

type Config struct {
    Name string   `cfg:"name"`
    Age  int      `cfg:"age"`
    Secret string `cfg:"secret" log:"-"` // skip this field in chu.MarshalMap
}

And load the configuration.

cfg := Config{}

if err := chu.Load(ctx, "test", &cfg); err != nil {
    return fmt.Errorf("failed to load config: %w", err)
}

slog.Info("loaded configuration", "config", chu.MarshalMap(ctx, cfg))

The configuration will be loaded from the following sources in order:
- Default
- File
- Http
- Environment

chu.MarshalMap or chu.MarshalJSON print the configuration, skipping the fields log:"false" tag and value unless 1, t, T, TRUE, true, True makes false.
String func use fmt.Stringer interface checks to print the configuration.

CONFIG_NAME_PREFIX env value can be used to set the prefix for the configuration.

Loaders

Check example folder to see how to use loaders with different kind of configuration.

Default

Default loader is used to set default values from tag default.

type Config struct {
    Name string `cfg:"name" default:"John"`
    Age  int    `cfg:"age"  default:"30"`
}

Default supports numbers, string, bool, time.Duration and pointer of that types.

Http

HTTP loader is used to load configuration from HTTP server.

Env Value Description Default
CONFIG_HTTP_ADDR HTTP server address, not exist than skips loader -
CONFIG_HTTP_PREFIX Prefix for the configuration -

It send GET request to the server with CONFIG_HTTP_ADDR env value with appending the name as path.
204 or 404 response code will skip the loader, only accept 200 response code.

File

File loader is used to load configuration from file.

First checking CONFIG_FILE env value and try current location to find in order of .toml, .yaml, .yml, .json extension with using given name.

Environment

Environment loader is used to load configuration from environment variables.

env or cfg tag can usable for environment loader.

export NAME=John
export AGE=30
type Config struct {
    Name string `cfg:"name"`
    Age  int    `cfg:"age"`
}

When loading configuration, usable to change env loader's options.

err := chu.Load(ctx, "my-app", &cfg,
    chu.WithLoaderOption(loader.NameEnv, loaderenv.New(
        loaderenv.WithPrefix("MY_APP_"),
    )),
)
Other Loaders

This loaders not enabled by default. Import the package to enable it.
Use chu.WithLoaderOption to set the loader options.
Or use chu.WithLoader to set the loaders manually.

#### Vault

Vault loader is used to load configuration from HashiCorp Vault.
This is not enabled by default.

Enable Vault loader importing the package.

import (
    _ "github.com/rakunlabs/chu/loader/loadervault"
)
Env Value Description Default
VAULT_SECRET_BASE_PATH Prefix for the configuration, must given base -
VAULT_ADDR VAULT_AGENT_ADDR Vault server address, not exist than skips loader -
VAULT_ROLE_ID Role ID for AppRole authentication, for role login -
VAULT_SECRET_ID Secret ID for AppRole authentication, for role login -
VAULT_APPROLE_BASE_PATH Base path for AppRole authentication, for role login auth/approle/login
#### Consul

Consul loader is used to load configuration from HashiCorp Consul.
This is not enabled by default.

Enable Consul loader importing the package.

import (
    _ "github.com/rakunlabs/chu/loader/loaderconsul"
)
Env Value Description Default
CONSUL_CONFIG_PATH_PREFIX Prefix for the configuration -
CONSUL_HTTP_ADDR Consul server address, not exist than skips loader -

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	DefaultLoaders = loader.Loaders
	DefaultHooks   = []loader.HookFunc{
		loader.HookTimeDuration,
	}
	DefaultOptions = []Option{}
)

Functions

func Load

func Load(ctx context.Context, name string, to any, opts ...Option) error

Load loads the configuration from loaders.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/rakunlabs/chu"
	"github.com/rakunlabs/chu/loader"
	"github.com/rakunlabs/chu/loader/loaderenv"
)

func main() {
	cfg := struct {
		Name string `cfg:"name"`
		Age  int    `cfg:"age"`
	}{}

	_ = os.Setenv("MY_APP_NAME", "another")
	_ = os.Setenv("MY_APP_AGE", "70")

	err := chu.Load(context.Background(), "my-app", &cfg, chu.WithLoaderOption(loader.NameEnv, loaderenv.New(loaderenv.WithPrefix("MY_APP_"))))
	if err != nil {
		fmt.Println("Error loading config:", err)
		return
	}

	fmt.Printf("%s\n", chu.MarshalJSON(cfg))
}
Output:

{"age":70,"name":"another"}

func MarshalJSON added in v0.2.1

func MarshalJSON(v any) []byte

func MarshalJSONE added in v0.2.1

func MarshalJSONE(v any) ([]byte, error)

Print is a function that takes a context and an interface{} value, and returns a JSON representation of the value.

  • Uses "log" tag and "-" to skip fields or false to skip

func MarshalMap added in v0.2.1

func MarshalMap(v any) any

func MarshalMapE added in v0.2.1

func MarshalMapE(v any) (any, error)

Types

type Option

type Option func(*option)

func WithHook

func WithHook(hooks ...loader.HookFunc) Option

WithHook adds hooks for conversion.

func WithHookSet

func WithHookSet(hooks ...loader.HookFunc) Option

WithHookSet sets the hooks for conversion.

func WithLoader added in v0.2.0

func WithLoader(name string, loader loader.LoadHolder) Option

func WithLoaderNames added in v0.1.4

func WithLoaderNames(names ...string) Option

WithLoaderNames sets the loaders inside default loaders use when loading the configuration.

func WithLoaderOption added in v0.2.0

func WithLoaderOption(name string, fn func() loader.Loader) Option

WithLoaderOption sets the loader option for the configuration.

  • name is the loader name
  • fn is the loader function
  • if the loader name is not exist, it will be ignored

func WithLogger

func WithLogger(logger logadapter.Adapter) Option

WithLogger sets the logger for logging.

func WithTag

func WithTag(tag string) Option

WithTag sets the tag for the configuration.

  • default is "cfg"

func WithWeaklyDashUnderscore

func WithWeaklyDashUnderscore(v bool) Option

WithWeaklyDashUnderscore sets the weakly dash underscore option.

  • default is false

func WithWeaklyIgnoreSeperator

func WithWeaklyIgnoreSeperator(v bool) Option

WithWeaklyIgnoreSeperator sets the weakly ignore separator option.

  • default is true

Jump to

Keyboard shortcuts

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