cfg

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2024 License: MIT Imports: 13 Imported by: 0

README

cfg

Simplified configuration for Go projects.

Automatically loads config files, .env, environment variables and command line arguments.

Allows you to define profiles, automatically loading files with the defined profile (e.g. config.yaml, config-dev.yaml, config-prod.yaml).

Docs: https://pkg.go.dev/github.com/go-path/cfg

How to use?

If you have a config file named config.json or confgi.yaml in the project root directory. Do.

var config = cfg.Global()

func init() {

    if err := config.Load(); err != nil {
		slog.Error(err.Error(), slog.Any("error", err))
		os.Exit(1)
	}

    slog.Info("My db connection:" + config.String("app.db.host"))
}

config.Load() initialize default settings. A variable is obtained respecting the order below.

  1. command line arguments (starting with "--", e.g. --server.port=9000)
  2. DotEnv file variables .env
  3. Operating system variables
  4. Profile specific configuration (config-{dev|prod|test}.{json,yaml,yml})
  5. global config (config.{json,yaml,yml})
  6. Default config (cfg.New(DefaultConfig))

If you want to change the configuration file name, use the SetFilePaths method (default is "config")

Methods

Get
  • config.Get(key string) any
  • config.Bool(key string) bool
  • config.Int(key string, def ...int) int
  • config.Float(key string, def ...float64) float64
  • config.String(key string, def ...string) string
  • config.Strings(key string, def ...[]string) []string
  • config.Duration(key string, def ...time.Duration) time.Duration
  • config.Time(key string, def ...time.Time) time.Time
  • config.DateTime(key string, def ...time.Time) time.Time
  • config.DateOnly(key string, def ...time.Time) time.Time
  • config.TimeOnly(key string, def ...time.Time) time.Time
  • config.TimeLayout(key string, layout string, def ...time.Time) time.Time
  • config.Keys(key string) []string
Set
  • config.Set(key string, value any)
  • config.SetString(key string, value string)
FileSystem
  • config.SetFileSystem(fs FileSystem)
  • config.SetFilePaths(filePaths ...string)
  • config.SetFileExt(ext string, fn UnmarshalFn)
  • config.SetProfileKey(profileKey string)

Loading

  • config.Load() error
  • config.LoadOsArgs(args []string)
  • config.LoadOsEnv()
  • config.LoadDotEnv() error
  • config.LoadEnviron(environ []string)
  • config.LoadObject(config O)
  • config.LoadFiles() error
  • config.LoadProfiles() error

Utils

  • config.Clone() *Env
  • config.Merge(src *Env)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(key string) bool

func DateOnly

func DateOnly(key string, def ...time.Time) time.Time

func DateTime

func DateTime(key string, def ...time.Time) time.Time

func Duration

func Duration(key string, def ...time.Duration) time.Duration

func Escape added in v1.0.4

func Escape(key string) string

func Float

func Float(key string, def ...float64) float64

func Get

func Get(key string) any

func Int

func Int(key string, def ...int) int

func JsonUnmarshal

func JsonUnmarshal(content []byte) (map[string]any, error)

func Load

func Load() error

func LoadDotEnv

func LoadDotEnv() error

func LoadEnviron

func LoadEnviron(environ []string)

func LoadFiles

func LoadFiles() error

func LoadObject

func LoadObject(config O)

func LoadOsArgs

func LoadOsArgs(args []string)

func LoadOsEnv

func LoadOsEnv()

func LoadProfiles

func LoadProfiles() error

func Merge

func Merge(src *Env)

func Segments added in v1.0.4

func Segments(key string) (segments []string)

Segments extract all key segments. (Ex. "assets.alias.bootstrap\.css.filepath" = ["assets", "alias", "bootstrap.css", "filepath"])

func SetFileExt

func SetFileExt(ext string, fn UnmarshalFn)

func SetFilePaths

func SetFilePaths(filePaths ...string)

func SetFileSystem

func SetFileSystem(fs FileSystem)

func SetProfileKey

func SetProfileKey(profileKey string)

func SetString

func SetString(key string, value string)

func String

func String(key string, def ...string) string

func Strings

func Strings(key string, def ...[]string) []string

func Time

func Time(key string, def ...time.Time) time.Time

func TimeLayout

func TimeLayout(key string, layout string, def ...time.Time) time.Time

func TimeOnly

func TimeOnly(key string, def ...time.Time) time.Time

func YamlUnmarshal added in v1.0.2

func YamlUnmarshal(content []byte) (map[string]any, error)

Types

type DefaultConfigFn

type DefaultConfigFn func(extra ...O) O

func CreateDefaultConfigFn

func CreateDefaultConfigFn(defaultValue O) DefaultConfigFn

CreateDefaultConfigFn simplifies the creation of default configurations

type Entry

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

Entry all properties are mapped to a data type below, in order to correctly respect the integration with Json

func ParseEntry

func ParseEntry(v any) *Entry

func (*Entry) Clone

func (e *Entry) Clone() *Entry

Clone makes a deep copy of the entry

func (*Entry) Kind

func (e *Entry) Kind() EntryKind

func (*Entry) Merge

func (e *Entry) Merge(other *Entry)

Merge merges two objects

func (*Entry) Value

func (e *Entry) Value() any

func (*Entry) Walk

func (e *Entry) Walk(visitor func(*Entry))

type EntryKind

type EntryKind uint

EntryKind represents the data types supported in the configuration, in order to maintain full compatibility with JSON files

const (
	BoolKind   EntryKind = iota // bool, for JSON booleans
	NumberKind                  // float64, for JSON numbers
	StringKind                  // string, for JSON strings
	ArrayKind                   // []*Entry{}, for JSON arrays
	ObjectKind                  // map[string]*Entry{}, for JSON objects
)

type Env

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

Env global instance.

func Clone

func Clone() *Env

func Global

func Global() *Env

func New

func New(defaults ...O) *Env

New default config

func (*Env) Bool

func (c *Env) Bool(key string) bool

Bool get a boolean value

func (*Env) Clone

func (c *Env) Clone() *Env

Clone make a copy of the config

func (*Env) DateOnly

func (c *Env) DateOnly(key string, def ...time.Time) time.Time

func (*Env) DateTime

func (c *Env) DateTime(key string, def ...time.Time) time.Time

func (*Env) Duration

func (c *Env) Duration(key string, def ...time.Duration) time.Duration

Duration get a duration from config

func (*Env) Float

func (c *Env) Float(key string, def ...float64) float64

Float get a floating value from a config

func (*Env) Get

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

Get a configuration property

func (*Env) Int

func (c *Env) Int(key string, def ...int) int

Int get an integer value from a config

func (*Env) Keys

func (c *Env) Keys(key string) []string

func (*Env) Load

func (c *Env) Load() error

Load initialize default settings. A variable is obtained respecting the order below.

1) command line arguments (starting with "--", e.g. --server.port=9000) 2) DotEnv file variables ".env" 3) Operating system variables 4) Profile specific configuration (config-{dev|prod|test}.json) 5) global config (config.json) 6) Default config (cfg.New(DefaultConfig))

func (*Env) LoadDotEnv

func (c *Env) LoadDotEnv() error

LoadDotEnv from https://github.com/joho/godotenv

func (*Env) LoadEnviron

func (c *Env) LoadEnviron(environ []string)

func (*Env) LoadFiles

func (c *Env) LoadFiles() error

LoadFiles processa arquivos de configuração

func (*Env) LoadObject

func (c *Env) LoadObject(config O)

LoadObject obtém as configurações a partir de um mapa em memória

func (*Env) LoadOsArgs

func (c *Env) LoadOsArgs(args []string)

LoadOsArgs will convert any command line option arguments (starting with ‘--’, e.g. --server.port=9000) to a property and add it to the Env.

Command line properties always take precedence over other property sources.

func (*Env) LoadOsEnv

func (c *Env) LoadOsEnv()

LoadOsEnv obtém todas as configurações do ambiente

func (*Env) LoadProfiles

func (c *Env) LoadProfiles() error

LoadProfiles processa arquivos de configuração (config.json)

func (*Env) Merge

func (c *Env) Merge(src *Env)

Merge merge src into the current config

func (*Env) Profiles added in v1.0.1

func (c *Env) Profiles() []string

Profiles get active profiles

func (*Env) Set

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

Set a configuration property

func (*Env) SetFileExt

func (c *Env) SetFileExt(ext string, fn UnmarshalFn)

SetFileExt define o processador para essa extensão de arquivo. Usado para suportar .yaml, .toml, .xml

func (*Env) SetFilePaths

func (c *Env) SetFilePaths(filePaths ...string)

SetFilePaths define o caminho dos arquivos de configuração.

func (*Env) SetFileSystem

func (c *Env) SetFileSystem(fs FileSystem)

SetFileSystem define a instância do FileSystem que será usado para carregamento

func (*Env) SetProfileKey

func (c *Env) SetProfileKey(profileKey string)

SetProfileKey define a key que identifica os arquivos de perfil de configuração.

func (*Env) String

func (c *Env) String(key string, def ...string) string

String get a string value

func (*Env) Strings

func (c *Env) Strings(key string, def ...[]string) []string

Strings get a string array values

func (*Env) Time

func (c *Env) Time(key string, def ...time.Time) time.Time

Time get a time from config

func (*Env) TimeLayout

func (c *Env) TimeLayout(key string, layout string, def ...time.Time) time.Time

TimeLayout get a time.Time using a layout

func (*Env) TimeOnly

func (c *Env) TimeOnly(key string, def ...time.Time) time.Time

type FileSystem

type FileSystem interface {
	Exists(filepath string) (bool, error)
	Read(filepath string) ([]byte, error)
}

FileSystem Represents access to the file system.

type O

type O map[string]any

represents a object, used to create default settings

func (O) Merge

func (o O) Merge(other O)

Merge merges the current object with the other without maintaining a reference

type UnmarshalFn

type UnmarshalFn func(content []byte) (map[string]any, error)

Jump to

Keyboard shortcuts

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