jety

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2026 License: 0BSD Imports: 11 Imported by: 4

README

JETY

test govulncheck

JSON, ENV, TOML, YAML

A lightweight Go configuration management library supporting JSON, ENV, TOML, and YAML formats. It provides viper-like AutomaticEnv functionality with fewer dependencies. Originally built to support grlx.

Installation

go get github.com/taigrr/jety

Requires Go 1.26.2 or later.

Quick Start

package main

import "github.com/taigrr/jety"

func main() {
    // Set defaults
    jety.SetDefault("port", 8080)
    jety.SetDefault("host", "localhost")

    // Environment variables are loaded automatically
    // e.g., PORT=9000 overrides the default

    // Read from config file
    jety.SetConfigFile("config.toml")
    jety.SetConfigType("toml")
    if err := jety.ReadInConfig(); err != nil {
        // handle error
    }

    // Get values (Set > env > config file > default)
    port := jety.GetInt("port")
    host := jety.GetString("host")
}

Features

  • Multiple formats: JSON, TOML, YAML
  • Automatic env loading: Environment variables loaded on init
  • Prefix filtering: Filter env vars by prefix (e.g., MYAPP_)
  • Case-insensitive keys: Keys normalized to lowercase
  • Type coercion: Getters handle type conversion gracefully
  • Thread-safe: Safe for concurrent access
  • Config precedence: Set() > environment > config file > defaults

Nested Configuration

For nested config structures like:

[services.cloud]
var = "xyz"
timeout = "30s"

[services.cloud.auth]
client_id = "abc123"

Use Sub() to get a scoped ConfigManager for a nested section:

cloud := jety.Sub("services")
if cloud != nil {
    inner := cloud.Sub("cloud")
    if inner != nil {
        varValue := inner.GetString("var")      // "xyz"
        timeout := inner.GetDuration("timeout")  // 30s
    }
}

Or access nested values directly with GetStringMap and type assertions:

services := jety.GetStringMap("services")
cloud := services["cloud"].(map[string]any)
varValue := cloud["var"].(string)  // "xyz"
Environment Variable Overrides

Environment variables use uppercase keys. For nested config, the env var name is the key in uppercase:

# Override top-level key
export PORT=9000

# For nested keys, use the full key name in uppercase
export SERVICES_CLOUD_VAR=override_value

With a prefix:

cm := jety.NewConfigManager().WithEnvPrefix("MYAPP_")
export MYAPP_PORT=9000
export MYAPP_SERVICES_CLOUD_VAR=override_value

Note: Environment variables override both defaults and config file values for registered keys (keys that appear in defaults or the config file). Nested env vars like SERVICES_CLOUD_VAR also apply to dot-notation lookups, GetStringMap, AllSettings, Unmarshal, and UnmarshalKey.

API

Configuration
Function Description
SetConfigFile(path) Set config file path
SetConfigDir(dir) Set config directory
SetConfigName(name) Set config file name (without extension)
SetConfigType(type) Set config type: "toml", "yaml", "json"
ReadInConfig() Read config file
WriteConfig() Write config to file
Values
Function Description
Set(key, value) Set a value
SetDefault(key, value) Set a default value
Sub(key) Get scoped sub-config
Get(key) Get raw value
GetString(key) Get as string
GetInt(key) Get as int
GetInt64(key) Get as int64
GetFloat64(key) Get as float64
GetBool(key) Get as bool
GetDuration(key) Get as time.Duration
GetStringSlice(key) Get as []string
GetIntSlice(key) Get as []int
GetStringMap(key) Get as map[string]any
IsSet(key) Check if key has a value
AllKeys() List all known keys
AllSettings() Get all values as a map
Unmarshal(target) Unmarshal config to struct
UnmarshalKey(key, target) Unmarshal a key to struct
Environment
Function Description
WithEnvPrefix(prefix) Filter env vars by prefix (strips prefix from keys)
SetEnvPrefix(prefix) Set prefix for env var lookups

Struct Unmarshaling

Unmarshal your configuration directly into Go structs:

type Config struct {
    Host    string `json:"host"`
    Port    int    `json:"port"`
    Debug   bool   `json:"debug"`
}

jety.SetConfigFile("config.json")
jety.SetConfigType("json")
jety.ReadInConfig()

var cfg Config
if err := jety.Unmarshal(&cfg); err != nil {
    log.Fatal(err)
}

For nested sections, use UnmarshalKey:

type DatabaseConfig struct {
    Host string `json:"host"`
    Port int    `json:"port"`
    Name string `json:"name"`
}

var dbCfg DatabaseConfig
if err := jety.UnmarshalKey("database", &dbCfg); err != nil {
    log.Fatal(err)
}

Struct tags use json:"..." since the unmarshaling uses JSON round-trip internally. Dot notation works with UnmarshalKey for deeply nested values (e.g., "services.api").

License

See LICENSE file.

Documentation

Overview

Package jety provides configuration management supporting JSON, ENV, TOML, and YAML formats.

It offers viper-like AutomaticEnv functionality with minimal dependencies, allowing configuration to be loaded from files and environment variables with automatic merging.

Configuration sources are layered with the following precedence (highest to lowest):

  • Values set via Set() or SetString()/SetBool()
  • Environment variables (optionally filtered by prefix)
  • Values from config file via ReadInConfig()
  • Default values set via SetDefault()

Basic usage:

jety.SetConfigFile("/etc/myapp/config.yaml")
jety.SetConfigType("yaml")
jety.SetEnvPrefix("MYAPP_")
jety.SetDefault("port", 8080)

if err := jety.ReadInConfig(); err != nil {
    log.Fatal(err)
}

port := jety.GetInt("port")

For multiple independent configurations, create separate ConfigManager instances:

cm := jety.NewConfigManager()
cm.SetConfigFile("/etc/myapp/config.toml")
cm.SetConfigType("toml")
cm.ReadInConfig()

Index

Constants

View Source
const (
	ConfigTypeTOML configType = "toml"
	ConfigTypeYAML configType = "yaml"
	ConfigTypeJSON configType = "json"
)

Variables

View Source
var (
	ErrConfigFileNotFound = errors.New("config file not found")
	ErrConfigFileEmpty    = errors.New("config file is empty")
)

Functions

func AllKeys added in v0.3.0

func AllKeys() []string

func AllSettings added in v0.3.0

func AllSettings() map[string]any

func ConfigFileUsed

func ConfigFileUsed() string

func Get added in v0.3.0

func Get(key string) any

func GetBool

func GetBool(key string) bool

func GetDuration

func GetDuration(key string) time.Duration

func GetFloat64 added in v0.4.0

func GetFloat64(key string) float64

func GetInt

func GetInt(key string) int

func GetInt64 added in v0.4.0

func GetInt64(key string) int64

func GetIntSlice

func GetIntSlice(key string) []int

func GetString

func GetString(key string) string

func GetStringMap

func GetStringMap(key string) map[string]any

func GetStringSlice

func GetStringSlice(key string) []string

func IsSet added in v0.3.0

func IsSet(key string) bool

func ReadInConfig

func ReadInConfig() error

func Set

func Set(key string, value any)

func SetBool added in v0.3.0

func SetBool(key string, value bool)

func SetConfigDir added in v0.3.0

func SetConfigDir(path string)

func SetConfigFile

func SetConfigFile(file string)

func SetConfigName

func SetConfigName(name string)

func SetConfigType

func SetConfigType(configType string) error

func SetDefault

func SetDefault(key string, value any)

func SetEnvPrefix

func SetEnvPrefix(prefix string)

func SetString added in v0.3.0

func SetString(key string, value string)

func Unmarshal added in v0.4.1

func Unmarshal(target any) error

func UnmarshalKey added in v0.4.1

func UnmarshalKey(key string, target any) error

func WriteConfig

func WriteConfig() error

Types

type ConfigManager

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

ConfigManager manages layered configuration from defaults, files, environment variables, and programmatic overrides.

func NewConfigManager

func NewConfigManager() *ConfigManager

NewConfigManager creates a new ConfigManager with all environment variables loaded. Use ConfigManager.WithEnvPrefix or ConfigManager.SetEnvPrefix to filter by prefix.

func Sub added in v0.4.0

func Sub(key string) *ConfigManager

func WithEnvPrefix added in v0.3.0

func WithEnvPrefix(prefix string) *ConfigManager

func (*ConfigManager) AllKeys added in v0.3.0

func (c *ConfigManager) AllKeys() []string

AllKeys returns all keys from all configuration sources, deduplicated.

func (*ConfigManager) AllSettings added in v0.3.0

func (c *ConfigManager) AllSettings() map[string]any

AllSettings returns all settings as a flat map of key to value.

func (*ConfigManager) ConfigFileUsed

func (c *ConfigManager) ConfigFileUsed() string

func (*ConfigManager) Get

func (c *ConfigManager) Get(key string) any

func (*ConfigManager) GetBool

func (c *ConfigManager) GetBool(key string) bool

func (*ConfigManager) GetDuration

func (c *ConfigManager) GetDuration(key string) time.Duration

func (*ConfigManager) GetFloat64 added in v0.4.0

func (c *ConfigManager) GetFloat64(key string) float64

func (*ConfigManager) GetInt

func (c *ConfigManager) GetInt(key string) int

func (*ConfigManager) GetInt64 added in v0.4.0

func (c *ConfigManager) GetInt64(key string) int64

func (*ConfigManager) GetIntSlice

func (c *ConfigManager) GetIntSlice(key string) []int

func (*ConfigManager) GetString

func (c *ConfigManager) GetString(key string) string

func (*ConfigManager) GetStringMap

func (c *ConfigManager) GetStringMap(key string) map[string]any

func (*ConfigManager) GetStringSlice

func (c *ConfigManager) GetStringSlice(key string) []string

func (*ConfigManager) IsSet added in v0.3.0

func (c *ConfigManager) IsSet(key string) bool

IsSet checks whether a key has been set in any configuration source.

func (*ConfigManager) ReadInConfig

func (c *ConfigManager) ReadInConfig() error

func (*ConfigManager) Set

func (c *ConfigManager) Set(key string, value any)

func (*ConfigManager) SetBool

func (c *ConfigManager) SetBool(key string, value bool)

func (*ConfigManager) SetConfigDir

func (c *ConfigManager) SetConfigDir(path string)

func (*ConfigManager) SetConfigFile

func (c *ConfigManager) SetConfigFile(file string)

func (*ConfigManager) SetConfigName

func (c *ConfigManager) SetConfigName(name string)

func (*ConfigManager) SetConfigType

func (c *ConfigManager) SetConfigType(ct string) error

func (*ConfigManager) SetDefault

func (c *ConfigManager) SetDefault(key string, value any)

func (*ConfigManager) SetEnvPrefix

func (c *ConfigManager) SetEnvPrefix(prefix string)

SetEnvPrefix filters environment variables to only those starting with the given prefix, stripping the prefix from key names.

func (*ConfigManager) SetString

func (c *ConfigManager) SetString(key string, value string)

func (*ConfigManager) Sub added in v0.4.0

func (c *ConfigManager) Sub(key string) *ConfigManager

Sub returns a new ConfigManager rooted at the given key. The key must refer to a map value (e.g., from a nested TOML/YAML/JSON section). The returned ConfigManager has the nested map loaded as its default config, and does not inherit the parent's environment prefix, overrides, or config file. Returns nil if the key does not exist or is not a map.

func (*ConfigManager) Unmarshal added in v0.4.1

func (c *ConfigManager) Unmarshal(target any) error

Unmarshal unmarshals the full combined configuration into the provided struct pointer. It works by marshaling the settings map to JSON and then unmarshaling into the target, so struct field tags should use `json:"key"`. The target must be a non-nil pointer to a struct.

func (*ConfigManager) UnmarshalKey added in v0.4.1

func (c *ConfigManager) UnmarshalKey(key string, target any) error

UnmarshalKey unmarshals a specific key's value into the provided struct pointer. The key must refer to a map value (e.g., a nested TOML/YAML/JSON section). Supports dot notation for nested keys.

func (*ConfigManager) WithEnvPrefix

func (c *ConfigManager) WithEnvPrefix(prefix string) *ConfigManager

WithEnvPrefix filters environment variables to only those starting with the given prefix, stripping the prefix from key names. Returns the ConfigManager for chaining.

func (*ConfigManager) WriteConfig

func (c *ConfigManager) WriteConfig() error

type ConfigMap

type ConfigMap struct {
	Key   string
	Value any
}

ConfigMap holds a configuration entry with its original key name and value.

Jump to

Keyboard shortcuts

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