xyconfig

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2023 License: MIT Imports: 19 Imported by: 0

README

xybor founder Go Reference GitHub Repo stars GitHub top language GitHub go.mod Go version GitHub release (release name instead of tag name) Codacy Badge Codacy Badge Go Report

Introduction

Package xyconfig supports to thread-safe read, control, and monitor configuration files.

Get started

var config = xyconfig.GetConfig("app")

// Read config from a string with the priority is 10.
config.ReadBytes(xyconfig.JSON, 10, []byte(`{"general": {"timeout": 3.14}}`))

// Read from files.
config.Read("config/10-default.ini")
config.Read("config/20-override.yml")
config.Read("10-dev.env")

// Load global environment variables to config files.
config.Read("env")

// Read config from aws s3 bucket.
config.Read("s3://bucket/30-item.ini")

fmt.Println(config.MustGet("general.timeout").MustFloat())

config.AddHook("general.timeout", func (e xyconfig.Event) {
    var timeout, ok = e.New.AsFloat()
    if !ok {
        return
    }
    SetTimeoutToSomeThing(timeout)
})

config.AddHook("general", func (e Event) {
    var general = e.New.MustConfig()
    var timeout = general.MustGet("timeout").MustFloat()
    SetTimeoutToSomething(timeout)
})

Benchmark

Operation Time Objects Allocated
Get 70 ns/op 0 allocs/op
ChangeConfig 413763 ns/op 724 allocs/op
WriteFile 335892 ns/op 3 allocs/op

Documentation

Overview

Package xyconfig supports to manage configuration files and real-time event-oriented watching.

Index

Examples

Constants

This section is empty.

Variables

View Source
var CastError = ConfigError.NewException("CastError")

CastError happens when the value cannot cast to a specific type.

View Source
var ConfigError = xyerror.NewException("ConfigError")

ConfigError represents for all error in xyconfig.

View Source
var ConfigKeyError = xyerror.Combine(ConfigError, xyerror.KeyError).NewException("ConfigKeyError")

ConfigKeyError happens when a key doesn't exist in Config.

View Source
var FormatError = ConfigError.NewException("FormatError")

FormatError represents for file format error.

Functions

This section is empty.

Types

type Config

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

Config contains configured values. It supports to read configuration files, watch their changes, and executes a custom hook when the change is applied.

A Config can contain many key-value pairs, or other Config instances.

Example
package main

import (
	"fmt"

	"github.com/xybor-x/xyconfig"
)

func main() {
	// Name your config object for global usage.
	var config = xyconfig.GetConfig("example")

	// Read config from a map.
	config.ReadMap(0, map[string]any{
		"general": map[string]any{
			"timeout": 3.14,
		},
	})

	// It's also ok if you want to read from string, byte array, or file with
	// supported formats.
	config.ReadJSON(0, []byte(`{"system": "linux"}`))

	// Read the config from file.
	// config.ReadFile("foo.json", false)
	// Or read and watch the file change.
	// config.ReadFile("foo.json", true)

	// You can get a key-value pair by many ways.
	var timeout = config.MustGet("general.timeout").MustFloat()
	fmt.Println("general.timeout =", timeout)

	var general = config.MustGet("general").MustConfig()
	fmt.Println("[general].timeout =", general.MustGet("timeout").MustFloat())

	general = xyconfig.GetConfig("example.general")
	fmt.Println("{general}.timeout =", general.MustGet("timeout").MustFloat())

	// You also can check if the key exist and the value is expected type.
	var system, ok = config.Get("system")
	if !ok {
		fmt.Println("Key system doesn't exist")
	}

	systemVal, ok := system.AsString()
	if !ok {
		fmt.Println("Key system is not a stringn")
	}

	fmt.Println("system =", systemVal)

}
Output:

general.timeout = 3.14
[general].timeout = 3.14
{general}.timeout = 3.14
system = linux

func GetConfig

func GetConfig(name string) *Config

GetConfig gets the existing Config instance by the name or creates a new one if it hasn't existed yet.

A Config instance is automatically created when new a dot-separated keys is added to the current Config. Its name is the dot-separated combination of the current Config's name and the its key.

For example, when the key "system.delimiter" is added to a Config named "app", a new Config is automatically created with the name "app.system". This Config instance contains key-value pair of "delimiter".

func (*Config) AddHook

func (c *Config) AddHook(key string, f func(e Event))

AddHook adds a hook function. This function will be executed when there is any change for values of the key.

The hook function is executed according to the following priority:

1. If a key is hooked by many functions in some Config instances, the hook function of the Config being closest with the key is executed.

2. If a key is hooked by many functions in a Config instance, the hook function with the most detailed key is executed.

Only one hook function is executed in a change.

For example, a change is applied for the key "general.system.timeout":

1. For the first case, the func2 is executed because c2 is the closer Config with "timeout".

var c1 = xyconfig.GetConfig("config")
var c2 = xyconfig.GetConfig("config.general")
c1.AddHook("general.system", func1)
c2.AddHook("system", func2)

2. For the second case, the func2 is executed because "general.system" is the more detailed key.

var c = xyconfig.GetConfig("config")
c.AddHook("general", func1)
c.AddHook("general.system", func2)
c.AddHook("general.os", func3)

func (*Config) CloseWatcher

func (c *Config) CloseWatcher() error

CloseWatcher closes the watcher.

func (*Config) Get

func (c *Config) Get(key string) (Value, bool)

Get returns the value assigned with the key. The latter returned value is false if they key doesn't exist.

func (*Config) GetDefault

func (c *Config) GetDefault(key string, def any) Value

GetDefault returns the value assigned with the key. It returns the default value if the key doesn't exist.

func (*Config) LoadEnv added in v1.3.0

func (c *Config) LoadEnv(d time.Duration) error

LoadEnv loads all environment variables and watch for their changes every duration. Set the duration as zero if no need to watch the change.

func (*Config) MustGet

func (c *Config) MustGet(key string) Value

MustGet returns the value assigned with the key. It panics if the key doesn't exist.

func (*Config) Read

func (c *Config) Read(path string) error

Read reads the config with any instance. If the instance is s3 url or environment variable, the watchInterval is used to choose the time interval for watching changes. If the instance is file path, it will watch the change if watchInterval > 0.

func (*Config) ReadBytes

func (c *Config) ReadBytes(format Format, priority int, b []byte) error

ReadBytes reads the config values from a bytes array under any format.

func (*Config) ReadENV added in v1.3.0

func (c *Config) ReadENV(priority int, b []byte) error

ReadENV reads the config values from a byte array under ENV format.

func (*Config) ReadFile

func (c *Config) ReadFile(filename string, watch bool) error

ReadFile reads the config values from a file. If watch is true, it will reload config when the file is changed.

func (*Config) ReadINI

func (c *Config) ReadINI(priority int, b []byte) error

ReadINI reads the config values from a byte array under INI format.

func (*Config) ReadJSON

func (c *Config) ReadJSON(priority int, b []byte) error

ReadJSON reads the config values from a byte array under JSON format.

func (*Config) ReadMap

func (c *Config) ReadMap(priority int, m map[string]any) error

ReadMap reads the config values from a map. If strict is false and the values of map are strings, it allows casting them to other types.

func (*Config) ReadS3 added in v1.4.0

func (c *Config) ReadS3(url string, d time.Duration) error

ReadS3 reads a file from AWS S3 bucket and watch for their changes every duration. Set the duration as zero if no need to watch the change.

You must provide the aws credentials in ~/.aws/credentials. The AWS_REGION is required.

func (*Config) Set

func (c *Config) Set(key string, value any, priority int, strict bool) bool

Set assigns the value to key. If the key doesn't exist, this method will create a new one, otherwise, it overrides the current value.

The return value says if a hook function is executed for this change.

func (*Config) SetWatchInterval added in v1.4.0

func (c *Config) SetWatchInterval(d time.Duration)

SetWatchInterval sets the time interval to watch the change when using Read() method.

func (*Config) ToMap added in v1.2.0

func (c *Config) ToMap() map[string]any

ToMap converts current config to map.

func (*Config) UnWatch

func (c *Config) UnWatch(filename string) error

UnWatch removes a filename from the watcher. This method also works with s3 url. Put "env" as parameter if you want to stop watching environment variables of LoadEnv().

type Event

type Event struct {
	// Key is the key of value (including all parent keys with dot-separated).
	Key string

	// Old is the value before the change.
	Old Value

	// New is the value after the change.
	New Value
}

Event represents for a changes in the config.

type Format

type Format int

Format represents supported file formats.

const (
	UnknownFormat Format = iota
	JSON
	INI
	ENV
)

Supported file formats.

type Value

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

Value instance represents for values in Config.

func (Value) AsArray

func (v Value) AsArray() ([]Value, bool)

AsArray returns the value as array. The latter return value is false if failed to cast.

func (Value) AsBool

func (v Value) AsBool() (val bool, ok bool)

AsBool returns the value as bool. The latter return value is false if failed to cast.

func (Value) AsConfig

func (v Value) AsConfig() (*Config, bool)

AsConfig returns the value as *Config. The latter return value is false if failed to cast.

func (Value) AsDuration added in v1.1.0

func (v Value) AsDuration() (time.Duration, bool)

AsDuration returns the value as time.Duration. The latter return value is false if failed to cast.

For example: 1s (1 second), 2m (2 minutes), 3h (3 hours), 4d (4 days), 5w (weeks).

func (Value) AsFloat

func (v Value) AsFloat() (float64, bool)

AsFloat returns the value as float64. The latter return value is false if failed to cast.

func (Value) AsInt

func (v Value) AsInt() (int, bool)

AsInt returns the value as int. The latter return value is false if failed to cast.

func (Value) AsString

func (v Value) AsString() (string, bool)

AsString returns the value as string. The latter return value is false if failed to cast.

func (Value) IsNil

func (v Value) IsNil() bool

IsNil return true if value is nil.

func (Value) MustArray

func (v Value) MustArray() []Value

MustArray returns the value as array. It panics if failed to cast.

func (Value) MustBool

func (v Value) MustBool() bool

MustBool returns the value as bool. It panics if failed to cast.

func (Value) MustConfig

func (v Value) MustConfig() *Config

MustConfig returns the value as *Config. It panics if failed to cast.

func (Value) MustDuration added in v1.1.0

func (v Value) MustDuration() time.Duration

MustDuration returns the value as time.Duration. It panics if failed to cast.

For example: 1s (1 second), 2m (2 minutes), 3h (3 hours), 4d (4 days), 5w (weeks).

func (Value) MustFloat

func (v Value) MustFloat() float64

MustFloat returns the value as float64. It panics if failed to cast.

func (Value) MustInt

func (v Value) MustInt() int

MustInt returns the value as int. It panics if failed to cast.

func (Value) MustString

func (v Value) MustString() string

MustString returns the value as string. It panics if failed to cast.

func (Value) String

func (v Value) String() string

String returns the string representation of Value.

Jump to

Keyboard shortcuts

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