Documentation
¶
Overview ¶
----------------------------------------------------------------------------- THIS IS UNABRIDGED DOCUMENTATION, PLEASE SEE THE README.md in the project root for more details. -----------------------------------------------------------------------------
package configdb provides convenient access methods to configuration stored as JSON or YAML.
Let's start with a simple YAML file config.yml:
development:
database:
host: localhost
users:
- name: calvin
password: yukon
- name: hobbes
password: tuna
production:
database:
host: 192.168.1.1
We can parse it using ParseYaml(), which will return a *Config instance on success:
c1 := (&config.InitContext{}).FromFile("config.yaml").Load().U()
An equivalent JSON configuration could be built using ParseJson():
c1 := (&config.InitContext{}).FromFile("config.json").Load().U()
From now, we can retrieve configuration values using a path in dotted notation:
// "localhost"
host := c1.DotP("development.database.host").String()
// or...
// "192.168.1.1"
host := c1.DotP("production.database.host").String()
Besides String(), other types can be fetched directly: Bool(), Float64(), Int(), Map() and List(). All these methods will issue an error if the path doesn't exist, or the value doesn't match or can't be converted to the requested type.
A nested configuration can be fetched using DotP(). Here we get a new *Config instance with a subset of the configuration:
c2 := c2.DotP("development")
Then the inner values are fetched relatively to the subset:
// "localhost"
host := c2.DotP("database.host").String()
For lists, the dotted path must use an index to refer to a specific value. To retrieve the information from a user stored in the configuration above:
// map[string]interface{}{ ... }
user1 := c1.DotP("development.users.0").Map()
// map[string]interface{}{ ... }
user2 := c1.DotP("development.users.1").Map()
// or...
// "calvin"
name1 := c1.DotP("development.users.0.name").String()
// "hobbes"
name2 := c1.DotP("development.users.1.name").String()
Index ¶
- Constants
- Variables
- func Extend_v2_any(a1 any, a2 any) any
- func ListAnyValue[T any](r *Root, defaultValueFunc ...func() []T) []T
- func ListValue[T any](r *Root, defaultValueFunc ...func() []T) (list_value []T)
- func MapAnyValue[T any](r *Root, defaultValueFunc ...func() map[string]T) map[string]T
- func MapValue[T any](r *Root, defaultValueFunc ...func() map[string]T) (map_value map[string]T)
- func MustRenderJson(c interface{}, oneline0indented1 int) (b []byte)
- func MustRenderYaml(c interface{}) []byte
- func PrintMemUsage()
- func RenderJson(c interface{}, oneline0indented1 int) (b []byte, err error)
- func RenderYaml(c interface{}) ([]byte, error)
- func TranslateEnvs_KeySuffix(s string) string
- func Value[T any](r *Root, defaultValueFunc ...func() T) (value T)
- type Command
- type CurrPath
- type ExpressionFailure
- type ISerkDataAPI
- type InitContext
- func (ic *InitContext) FromBytes(data []byte, hashes ...string) *InitContext
- func (ic *InitContext) FromFile(fileName string, hashes ...string) *InitContext
- func (ic *InitContext) GetTracer() (tracer loggeterrapi.ITracer)
- func (ic *InitContext) Load() *Root
- func (ic *InitContext) LoadWithParenting() (result *Root)
- func (ic *InitContext) WithErr(err **controlflow.Event) *InitContext
- func (ic *InitContext) WithOk(ok *bool) *InitContext
- func (ic *InitContext) WithTracer(tracer loggeterrapi.ITracer) *InitContext
- type Location
- type MsgCmd
- type MsgCommitSignal
- type NewSource_Options
- type Root
- func (r *Root) At(pathParts ...string) *Root
- func (r *Root) Bool(defaultValueFunc ...func() bool) bool
- func (r *Root) BytesFromBase64(defaultValueFunc ...func() []byte) []byte
- func (r *Root) ChildCopy() (c2 *Root)
- func (r *Root) DDash()
- func (r *Root) DoPanic() (c2 *Root)
- func (r *Root) DontPanic() (c2 *Root)
- func (r *Root) DotP(path string) *Root
- func (r *Root) Duration(defaultValueFunc ...func() time.Duration) time.Duration
- func (r *Root) ExtendBy(c2 *Root) *Root
- func (r *Root) ExtendByEnvsV2_WithPrefix(prefix string, transformerFuncs ...func(s string) string)
- func (r *Root) ExtendByEnvs_WithPrefix(prefix string) *Root
- func (r *Root) ExtendByLocalMap(m map[string]any)
- func (r *Root) ExtendBy_v2(c2 *Root) *Root
- func (r *Root) Float64(defaultValueFunc ...func() float64) float64
- func (r *Root) GetCurrentLocationPlusPath(pathParts ...string) (path []string)
- func (r *Root) GetTracer() (tracer loggeterrapi.ITracer)
- func (r *Root) Int(defaultValueFunc ...func() int) int
- func (r *Root) List(defaultValueFunc ...func() []any) []any
- func (r *Root) ListDuration(defaultValueFunc ...func() []time.Duration) []time.Duration
- func (r *Root) ListFloat64(defaultValueFunc ...func() []float64) []float64
- func (r *Root) ListInt(defaultValueFunc ...func() []int) []int
- func (r *Root) ListRoot() []*Root
- func (r *Root) ListString(defaultValueFunc ...func() []string) []string
- func (r *Root) ListTime(defaultValueFunc ...func() []time.Time) []time.Time
- func (r *Root) Map(defaultValueFunc ...func() map[string]any) map[string]any
- func (r *Root) MapBool(defaultValueFunc ...func() map[string]bool) map[string]bool
- func (r *Root) MapDuration(defaultValueFunc ...func() map[string]time.Duration) map[string]time.Duration
- func (r *Root) MapFloat64(defaultValueFunc ...func() map[string]float64) map[string]float64
- func (r *Root) MapInt(defaultValueFunc ...func() map[string]int) map[string]int
- func (r *Root) MapRoot() map[string]*Root
- func (r *Root) MapString(defaultValueFunc ...func() map[string]string) map[string]string
- func (r *Root) MapTime(defaultValueFunc ...func() map[string]time.Time) map[string]time.Time
- func (r *Root) P(pathParts ...string) *Root
- func (r *Root) PP(path string) *Root
- func (r *Root) ResetErrAndOk() *Root
- func (r *Root) Set(mode int, pathParts []string, v interface{})
- func (r *Root) SetPP(mode int, path string, v any)
- func (r *Root) SlashP(path string) *Root
- func (r *Root) String(defaultValueFunc ...func() string) string
- func (r *Root) TheIsa()
- func (r *Root) Time(defaultValueFunc ...func() time.Time) time.Time
- func (r *Root) UpgradeMMode(mode int)
- func (r *Root) WithErr(err **controlflow.Event) (c2 *Root)
- func (r *Root) WithOk(okRef *bool) (c2 *Root)
- func (r *Root) WithTracer(tracer loggeterrapi.ITracer) *Root
- type SerkAdapterAsync
- type SerkAdapterSync
- type Source
- type TreeTraversalContext
Constants ¶
const ( SingleThread = 0xde71f0ea SyncX = 0x10cf2934 SyncX_NP = 0xc00e58f5 Enqueue = 0x3c248530 )
const ( ExpressionStatus_0_Norm = iota ExpressionStatus_1_Failed ExpressionStatus_2_DefaultCallbackAlreadyUsedOnce )
Variables ¶
var ErrMsg_MultipleCallbackWithoutPriorErrOk = "default value callback used multiple times, without prior ErrOk()"
var ReEnvs01 = regexp.MustCompile(`\W`)
Functions ¶
func ListAnyValue ¶ added in v3.21.0
Gets a []any, and returns the []T See also the ListValue()
func ListValue ¶ added in v3.17.0
Does a simple type assertion, isn't a replacement for specific accessors See also the ListAnyValue()
func MapAnyValue ¶ added in v3.21.0
Gets a map[string]any, and return the map[string]T See also the MapValue()
func MapValue ¶ added in v3.17.0
Does a simple type assertion, isn't a replacement for specific accessors See also the MapAnyValue()
func MustRenderJson ¶ added in v3.3.0
func MustRenderYaml ¶ added in v3.3.0
func MustRenderYaml(c interface{}) []byte
func PrintMemUsage ¶
func PrintMemUsage()
PrintMemUsage outputs the current, total and OS memory being used. As well as the number of garage collection cycles completed.
func RenderJson ¶
func RenderYaml ¶
func TranslateEnvs_KeySuffix ¶
Does this replacements:
p__ -> "." (point) d__ -> "-" (dash) u__ -> "__" (underscore) D__ -> "$" (dollar) A__ -> "@" (at)
For example, the line "Somethingp__superd__duperp__D__isa" will become "Something.super-duper.$isa". Because the key is located at the end of words, this makes minimal possible impact on readability.
Types ¶
type ExpressionFailure ¶
type ExpressionFailure int
type InitContext ¶
type InitContext struct {
MMode int
CurrentFileName string
SourceHashesRequired []string
SourceHashesActual []string
RawData []byte
ErrPtrPtr **controlflow.Event
OkPtr *bool
// contains filtered or unexported fields
}
func (*InitContext) FromBytes ¶
func (ic *InitContext) FromBytes(data []byte, hashes ...string) *InitContext
func (*InitContext) FromFile ¶
func (ic *InitContext) FromFile(fileName string, hashes ...string) *InitContext
func (*InitContext) GetTracer ¶ added in v3.10.0
func (ic *InitContext) GetTracer() (tracer loggeterrapi.ITracer)
func (*InitContext) Load ¶
func (ic *InitContext) Load() *Root
func (*InitContext) LoadWithParenting ¶
func (ic *InitContext) LoadWithParenting() (result *Root)
func (*InitContext) WithErr ¶ added in v3.10.0
func (ic *InitContext) WithErr(err **controlflow.Event) *InitContext
func (*InitContext) WithOk ¶ added in v3.10.0
func (ic *InitContext) WithOk(ok *bool) *InitContext
func (*InitContext) WithTracer ¶ added in v3.10.0
func (ic *InitContext) WithTracer(tracer loggeterrapi.ITracer) *InitContext
type MsgCommitSignal ¶ added in v3.32.0
type MsgCommitSignal struct {
ChDown chan struct{}
}
type NewSource_Options ¶
type Root ¶ added in v3.6.0
type Root struct {
Data any
OkPtr *bool
ErrPtrPtr **controlflow.Event
ExpressionStatus ExpressionFailure
Source *Source `json:"-"`
InitContext *InitContext `json:"-"`
// contains filtered or unexported fields
}
Root represents a configuration with convenient access methods.
func (*Root) BytesFromBase64 ¶ added in v3.6.0
func (*Root) ChildCopy ¶ added in v3.6.0
Makes a copy of Config struct. The actual data is linked by reference.
func (*Root) DontPanic ¶ added in v3.10.0
Sets dontPanicFlag=true, so that failing operations won't panic, if there's no Err or Ok set. Getters will return default null values.
func (*Root) DotP ¶ added in v3.6.0
DotP - dot-path traversal. Path example: "qqq.www.eee.12" Synonym for PP(). Can only traverse the hierarchy of []any and map[string]any types only.
func (*Root) ExtendBy ¶ added in v3.6.0
ExtendBy() extends current config with another config: i.e. all values from another config are added to the current config, and overwritten with new values if already present. It implements limited prototype-based inheritance. It does not add elements, if not present in the prototype. Note that if you extend with different structure type you will get an error. See: `.Set()` method for details.
func (*Root) ExtendByEnvsV2_WithPrefix ¶ added in v3.6.0
Unlike the ExtendByEnvs_WithPrefix(), this function allows to create new nodes in the config, based on the envs. It scans all envs matching the specified prefix, then strips the prefix, then what is left is used as a valid dot-path as is. For example, if the prefix was PRFX, and you specify an env var "PRFX_asd-qwe.zxc.123", then this variable will be set, and created if necessary, the node at path "asd-qwe.zxc.123". If such names are supported in your OS is up to you, but see the https://stackoverflow.com/questions/2821043/allowed-characters-in-linux-environment-variable-names. Update: As it turns out, the OS may support it, but the bash didn't, and so you can use it. To solve this issue, I am adding a transformation callback, which can additionally transform the path string, so you can avoid using non-alphanumerics in env names. See also the TranslateEnvs_KeySuffix().
func (*Root) ExtendByEnvs_WithPrefix ¶ added in v3.6.0
Fetch data from system env using prefix, based on existing config keys. The algorithm: for all possible paths in config do { join by "_"; make uppercase; remove all punctuation except "_"; add prefix; lookup if there is an env with that name; if it is - get its value and set to the config at the path}. VERY IMPORTANT USAGE NOTE: this can override what is already present in the config, but it cannot create new things, which were not in the configdb.
In case of OS environment all existing at the moment of parsing keys will be scanned in OS environment, but in uppercase and the separator will be `_` instead of a `.`. If EnvPrefix() is used the given prefix will be used to lookup the environment variable, e.g PREFIX_FOO_BAR will set foo.bar. In case of flags separator will be `-`. In case of command line arguments possible to use regular dot notation syntax for all keys. For see existing keys we can run application with `-h`.
func (*Root) ExtendByLocalMap ¶ added in v3.22.0
Works similar to extention with envs, but gets the values from the local map. Primary use is to pass local variables to a boot config on service startup. Allows to create new nodes in the config. The keys are used as a valid dot-path as is. For example, if you specify an key "asd-qwe.zxc.123", then this variable will set, and created if necessary, the node at path "asd-qwe.zxc.123".
func (*Root) ExtendBy_v2 ¶ added in v3.6.0
ExtendBy() extends current config with another config: i.e. all values from another config are added to the current config, and overwritten with new values if already present. It implements prototype-based inheritance.
func (*Root) GetCurrentLocationPlusPath ¶ added in v3.6.0
func (*Root) GetTracer ¶ added in v3.10.0
func (r *Root) GetTracer() (tracer loggeterrapi.ITracer)
func (*Root) ListDuration ¶ added in v3.6.0
func (*Root) ListFloat64 ¶ added in v3.6.0
func (*Root) ListString ¶ added in v3.6.0
func (*Root) MapDuration ¶ added in v3.6.0
func (*Root) MapFloat64 ¶ added in v3.6.0
func (*Root) P ¶ added in v3.6.0
Traverses the struct down the path. P() does not create a path, if it didn't exist. So, if used before Set(), it will take you as far as there is something, not farther. Can only traverse the hierarchy of []any and map[string]any types only.
func (*Root) PP ¶ added in v3.6.0
PP - point-path traversal. Path example: "qqq.www.eee.12" Synonym for DotP(). Can only traverse the hierarchy of []any and map[string]any types only.
func (*Root) ResetErrAndOk ¶ added in v3.10.0
Resets any errors, accumulated in previous expressions on this Config object. Sets Ok=true, Err=nil, ExpressionStatus=0_Norm, if any
func (*Root) Set ¶ added in v3.6.0
Sets a nested config according to a path, relative from current location. Without a Source object set, acts as a by-pass to the NonThreadSafe_Set(). If you don't want to specify path, and just want to use it from current location, then invoke with nil path, c.Set(nil, value) In Enqueue mode it is totally asynchronous, and it's effect is somewhat delayed. Use explicit commit signal if you want to synchronize explicitly. P() does not create a path, if it didn't exist. So, if used before Set(), it will take you as far as there is something, not farther.
func (*Root) SlashP ¶ added in v3.6.0
SlashP - slash-path traversal. Path example: "qqq/www/eee/12" Can only traverse the hierarchy of []any and map[string]any types only.
func (*Root) UpgradeMMode ¶ added in v3.32.0
func (*Root) WithErr ¶ added in v3.10.0
func (r *Root) WithErr(err **controlflow.Event) (c2 *Root)
Attaches an err error variable to the expression, by reference. Make sure to reset it to nil when reusing between expressions.
func (*Root) WithOk ¶ added in v3.10.0
Attaches a ok bool variable to the expression, by reference, with it's current value. Failures in subsequent operations may set it to false only, so make sure its current state is true.
func (*Root) WithTracer ¶ added in v3.10.0
func (r *Root) WithTracer(tracer loggeterrapi.ITracer) *Root
Can be used to set specific tracer if you expect this node to raise exceptions
type SerkAdapterAsync ¶
type SerkAdapterAsync struct {
CS *Source
}
thread-safe
func (*SerkAdapterAsync) Test ¶
func (a *SerkAdapterAsync) Test()
type SerkAdapterSync ¶
type SerkAdapterSync struct {
C *Root
}
thread-unsafe
func (*SerkAdapterSync) Test ¶
func (a *SerkAdapterSync) Test()
type Source ¶
type Source struct {
Root *Root
ChCmd chan *MsgCmd
ChCommitSignal chan *MsgCommitSignal
Opts *NewSource_Options
}
The source is where the root stems from
func NewSource ¶
func NewSource(f ...func(opts *NewSource_Options)) (s *Source)
func (*Source) SyncWaitCommitted ¶ added in v3.32.0
func (s *Source) SyncWaitCommitted()
type TreeTraversalContext ¶
type TreeTraversalContext struct {
// contains filtered or unexported fields
}
Source Files
¶
- 1-init-context.go
- 2-source.go
- 3-iroot.go
- 3-root-set.go
- 3-root.go
- accessors-duration.go
- accessors-generic-value.go
- accessors-lists.go
- accessors-maps.go
- accessors-primitives.go
- accessors-time.go
- bytes-from-base64.go
- constants.go
- curr-path.go
- ddash.go
- doc.go
- extend-envs.go
- extend-local-map.go
- extend-olebedev.go
- extend-v2.go
- isa.go
- private.go
- serk-api-tmpplug.go
- serk-async.go
- serk-sync.go
- tree-traversal.go
- w-json.go
- w-yaml.go
- z-misc.go
