uconfig

package
v0.0.0-...-969647d Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2024 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package uconfig enables access to the configuration loaded by uboot / golum.

This is typically YAML that looks like this:

properties:
  key:        value
  anInt:      10

autoreload:   true

debug:

components:
  - name:     instanceName
    type:     serviceType
    note:     a note about this
    disabled: false
    hosts:    ["optional", "hosts", "enabled", "on"]
    config:
      foo:    1
      bar:    hello there
      sub:
        foo:  2
        bar:  "{{.key}}"
      array:
        - foo: "{{.anInt}}"
          bar: array element 0
        - foo: 5
          bar: array element 1
      ...
  - name:     instance2Name
    type:     service2Type
    config:
      ...

Properties

The properties section provides substitutable values that can be used in later sections. Properties can use substitutions from other properties.

As string values are accessed, the values also become properties for expanding later accessed string values.

Expansion occurs when a string value contains ${VAR} or {{.KEY}}.

The ${VAR} will be filled in with ENV variables, if available.

The {{.KEY}} will be filled in with properties as per the go text/template package.

properties:
  key:        value
  fromEnv:    ${ENV_VAR}
  basedOnKey: {{.key}}    # NOTE: the '.' is critical

All golang text template rules apply.

The following properties are automatically added:

  • homeDir - the home dir of the user
  • thisUser - the username of the user
  • thisHost - the hostname (nodename) of the host
  • thisIp - the first listed (non loopback) IP
  • thisProcess - the process name of the process
  • thisDir - where the process is installed
  • initDir - where the process is started from

Includes

Other files can be included with the 'include_' directive, as in:

include_: /path/to/file.yml

Sections

Each component has a config section. A config section may contain sub-sections and arrays of sub-sections.

Index

Constants

View Source
const (
	PROPS = "properties"

	MaxUint = ^uint(0)
	MaxInt  = int(MaxUint >> 1)
	MinInt  = -MaxInt - 1
)
View Source
const (
	ErrStringBlank    = uerr.Const("String value empty")
	ErrStringNotBlank = uerr.Const("String value not empty")
)

Variables

View Source
var (
	ThisHost    = ""
	ThisIp      = ""
	ThisProcess = "" // set by boot
	LocalAddrs  = make(map[string]bool)
	ThisD       = ""
	InitD       = initInitD()    // initial dir upon exec
	InstallD    = initInstallD() // where we're installed
	DryRun      = false
)

Functions

func Assign

func Assign(name string, dst, src any) (err error)

make sure types are assignable, then assign

var it any
...
var toMap map[string]bool
err := Assign( "context", &toMap, it )

func EnsureAddr

func EnsureAddr(defaultHost, defaultPort, addr string) (rv string, err error)

Ensure addr is correctly filled in with default host/port if missing.

addr may be any of these:

HOST:PORT
""
:
HOST
HOST:
:PORT
[HOST]:PORT
[IPv6]:PORT

HOST may be an IP (v4 or v6), hostname, or fqdn.

The square brackets can only be used when PORT is also provided. And they must be used when HOST is an IPv6 address.

func Float64FromBitRateString

func Float64FromBitRateString(s string) (rv float64, err error)

convert a string to an float64 bit rate, taking into account SI prefixes: K, M, G, T, P: base 1000 multipliers

func Float64FromByteSizeString

func Float64FromByteSizeString(s string) (rv float64, err error)

convert a string to an float64 byte size, taking into account SI prefixes: K, M, G, T, P: treat as base 1024 multipliers Ki, Mi, Gi, Ti, Pi: base 1024 multipliers

func Float64FromSiString

func Float64FromSiString(s string) (rv float64, err error)

convert a string to an float64, taking into account SI prefixes: K, M, G, T, P: base 1000 multipliers Ki, Mi, Gi, Ti, Pi: base 1024 multipliers

func InitEnv

func InitEnv() (err error)

record some info about the environment

func IntFromBitRateString

func IntFromBitRateString[I Int](s string, rv *I) (err error)

convert a string to an int64 bit rate, taking into account SI prefixes: K, M, G, T, P: base 1000 multipliers

also handled: - if string begins with "0x", then it is hex - if string begins with "0", then it is octal

func IntFromByteSizeString

func IntFromByteSizeString[I Int](s string, rv *I) (err error)

convert a string to an int64 byte size, taking into account SI prefixes: K, M, G, T, P: treat as base 1024 multipliers Ki, Mi, Gi, Ti, Pi: base 1024 multipliers

also handled: - if string begins with "0x", then it is hex - if string begins with "0", then it is octal

func IntFromSiString

func IntFromSiString[I Int](s string, rv *I) (err error)

convert a string to an int64, taking into account SI prefixes: K, M, G, T, P: base 1000 multipliers Ki, Mi, Gi, Ti, Pi: base 1024 multipliers

also handled: - if string begins with "0x", then it is hex - if string begins with "0", then it is octal

func IsLocalUrl

func IsLocalUrl(url *nurl.URL) bool

func IsThisHost

func IsThisHost(host string) bool

is the specified host a known hostname or IP of the host we're running on?

func UIntFromBitRateString

func UIntFromBitRateString[U UInt](s string, rv *U) (err error)

convert a string to an uint64 bit rate, taking into account SI prefixes: K, M, G, T, P: base 1000 multipliers

also handled: - if string begins with "0x", then it is hex - if string begins with "0", then it is octal

func UIntFromByteSizeString

func UIntFromByteSizeString[U UInt](s string, rv *U) (err error)

convert a string to an uint64 byte size, taking into account SI prefixes: K, M, G, T, P: treat as base 1024 multipliers Ki, Mi, Gi, Ti, Pi: base 1024 multipliers

also handled: - if string begins with "0x", then it is hex - if string begins with "0", then it is octal

func UIntFromSiString

func UIntFromSiString[U UInt](s string, rv *U) (err error)

convert a string to an uint64, taking into account SI prefixes: K, M, G, T, P: base 1000 multipliers Ki, Mi, Gi, Ti, Pi: base 1024 multipliers

also handled: - if string begins with "0x", then it is hex - if string begins with "0", then it is octal

func UserInfo

func UserInfo() (userName string, homeD string)

func ValidHostname

func ValidHostname(s string) bool

check with net.ParseIP first to rule out if it is an IP addr

func YamlLoad

func YamlLoad(file string, target any) (err error)

load the YAML file into target, which may be a ptr to map or ptr to struct

Types

type Array

type Array struct {
	Context string
	// contains filtered or unexported fields
}

an array of config sections

func ArrayFromSection

func ArrayFromSection(s *Section) (rv *Array)

func (*Array) Append

func (this *Array) Append(s *Section)

func (*Array) DumpSubs

func (this *Array) DumpSubs() string

func (*Array) Each

func (this *Array) Each(visitor Visitor) (err error)

iterate through the sections, aborting of visitor returns an error

func (*Array) Empty

func (this *Array) Empty() bool

func (*Array) Get

func (this *Array) Get(i int) *Section

get the i'th section from this

func (*Array) Len

func (this *Array) Len() int

type Builder

type Builder func(config *Chain) (rv any, err error)

Builder works with Chain.Build, Chain.BuildIf, Chain.BuildFrom to build rv from config.

type Chain

type Chain struct {
	Section *Section
	Error   error
}

Chain provides a nicer means of accessing a config Section.

Chain allows chaining of accessor functions to avoid error checking boilerplate.

The accessor functions enable accessing the config settings and sub-sections.

The accessors also perform sensible type coercion. For example, if a setting is a string, but it is being accessed as an int, then it will be converted to an int if possible.

Validation funcs are also provided, or you can make your own.

A Section is usually provided to you in the golum lifecycle methods for creating or reloading your component. It is simple to convert it to a Chain.

var s *uconfig.Section
var foo, bar, baz int

err = s.Chain().
    GetInt("foo", &foo).
    GetInt("bar", &bar, uconfig.MustBePos).
    GetInt("baz", &baz, uconfig.ValidRange(5, 20)).
    Each("array",
        func(c *Chain) (err error) {
            return c.
                ...
                Done()
        }
    Done()

func FromFile

func FromFile(f string) *Chain

open file and read config from it

func (*Chain) ASection

func (this *Chain) ASection(key string, visitor Visitor) *Chain

deprecated - use Must().

get the sub-section specified by key and process it

func (*Chain) Build

func (this *Chain) Build(value any, builder Builder) *Chain

build value from current config section using builder

if builder returns nil, then no assignment is made to value

value is typically a pointer to the thing that will be built. If the thing to be built is a pointer, then it must be the addres of the pointer.

func (*Chain) BuildFrom

func (this *Chain) BuildFrom(
	key string,
	value any,
	builder Builder,
) *Chain

build value from named config section

if builder returns nil, then no assignment is made to value

value is typically a pointer to the thing that will be built. If the thing to be built is a pointer, then it must be the addres of the pointer.

func (*Chain) BuildIf

func (this *Chain) BuildIf(key string, value any, builder Builder) *Chain

build value from named config section if it exists

if builder returns nil, then no assignment is made to value

value is typically a pointer to the thing that will be built. If the thing to be built is a pointer, then it must be the addres of the pointer.

func (*Chain) Construct

func (this *Chain) Construct(target Constructable) *Chain

Construct target from current config section.

func (*Chain) ConstructFrom

func (this *Chain) ConstructFrom(key string, target Constructable) *Chain

Construct target from named config sub-section.

func (*Chain) ConstructIf

func (this *Chain) ConstructIf(key string, target Constructable) *Chain

Construct target from named config sub-section if sub-section exists.

func (*Chain) Done

func (this *Chain) Done() error

end the accessor chain, detecting invalid config, returning active error (if any)

func (*Chain) DumpProps

func (this *Chain) DumpProps() string

func (*Chain) Each

func (this *Chain) Each(key string, builder ChainVisitor) *Chain

run builder against each sub section in named array

func (*Chain) EachIf

func (this *Chain) EachIf(key string, builder ChainVisitor) *Chain

run builder against each sub section in named array, if array exists

func (*Chain) EachSection

func (this *Chain) EachSection(key string, visitor Visitor) *Chain

deprecated - use Each().

get the array specified by key and iterate through the contained sections

func (*Chain) EachSectionIf

func (this *Chain) EachSectionIf(key string, visitor Visitor) *Chain

deprecated - use EachIf().

get the array specified by key if it exists and iterate through the sections.

func (*Chain) FailExtraKeys

func (this *Chain) FailExtraKeys(allowedKeys ...string) *Chain

func (*Chain) GetArray

func (this *Chain) GetArray(key string, value **Array) *Chain

prefer Each()

func (*Chain) GetArrayIf

func (this *Chain) GetArrayIf(key string, value **Array) *Chain

prefer EachIf()

func (*Chain) GetBitRate

func (this *Chain) GetBitRate(
	key string,
	result any,
	validators ...IntValidator,
) *Chain

func (*Chain) GetBool

func (this *Chain) GetBool(key string, value *bool) *Chain

func (*Chain) GetByteSize

func (this *Chain) GetByteSize(
	key string,
	result any,
	validators ...IntValidator,
) *Chain

func (*Chain) GetChain

func (this *Chain) GetChain(key string, value **Chain) *Chain

func (*Chain) GetCreateDir

func (this *Chain) GetCreateDir(
	key string,
	value *string,
	perm os.FileMode,
) *Chain

func (*Chain) GetDuration

func (this *Chain) GetDuration(key string, value *time.Duration) *Chain

func (*Chain) GetFloat64

func (this *Chain) GetFloat64(
	key string,
	value *float64,
	validators ...FloatValidator,
) *Chain

func (*Chain) GetInt

func (this *Chain) GetInt(
	key string,
	result any,
	validators ...IntValidator,
) *Chain

func (*Chain) GetInts

func (this *Chain) GetInts(
	key string,
	result *[]int,
	validators ...IntValidator,
) *Chain

func (*Chain) GetIt

func (this *Chain) GetIt(key string, value *any) *Chain

if key resolves to some value, then set value

func (*Chain) GetMillis

func (this *Chain) GetMillis(key string, value *int64, validators ...IntValidator,
) *Chain

func (*Chain) GetPath

func (this *Chain) GetPath(key string, value *string) *Chain

func (*Chain) GetPosInt

func (this *Chain) GetPosInt(key string, value *int) *Chain

func (*Chain) GetRawString

func (this *Chain) GetRawString(
	key string,
	result *string,
	validators ...StringValidator,
) *Chain

get raw string value with no detemplating or translation

func (*Chain) GetRegexp

func (this *Chain) GetRegexp(key string, value **regexp.Regexp) *Chain

func (*Chain) GetRegexpIf

func (this *Chain) GetRegexpIf(key string, value **regexp.Regexp) *Chain

func (*Chain) GetSection

func (this *Chain) GetSection(key string, value **Section) *Chain

deprecated

func (*Chain) GetSectionIf

func (this *Chain) GetSectionIf(key string, value **Section) *Chain

deprecated

func (*Chain) GetString

func (this *Chain) GetString(
	key string,
	result *string,
	validators ...StringValidator,
) *Chain

if key resolves to string, then set result

func (*Chain) GetStringMap

func (this *Chain) GetStringMap(key string, value *map[string]string) *Chain

if key resolves to map[string]string, then set value

func (*Chain) GetStrings

func (this *Chain) GetStrings(
	key string,
	result *[]string,
	validators ...StringValidator,
) *Chain

if key resolves to []string, then set result

func (*Chain) GetUInt

func (this *Chain) GetUInt(
	key string,
	result any,
	validators ...UIntValidator,
) *Chain

func (*Chain) GetUrl

func (this *Chain) GetUrl(
	key string,
	value **nurl.URL,
	validators ...StringValidator,
) *Chain

func (*Chain) GetUrlIf

func (this *Chain) GetUrlIf(
	key string,
	value **nurl.URL,
	validators ...StringValidator,
) *Chain

func (*Chain) GetValidInt

func (this *Chain) GetValidInt(key string, invalid int, value *int) *Chain

func (*Chain) GetValidIt

func (this *Chain) GetValidIt(key string, value *any) *Chain

if key resolves to some value, then set value, otherwise error

func (*Chain) GetValidPath

func (this *Chain) GetValidPath(key string, value *string) *Chain

func (*Chain) If

func (this *Chain) If(key string, builder ChainVisitor) *Chain

run builder with specified sub-section if section exists

func (*Chain) IfHasKeysIn

func (this *Chain) IfHasKeysIn(f ChainVisitor, keys ...string) *Chain

if any of the keys are present, call handler

func (*Chain) IfHasKeysMatching

func (this *Chain) IfHasKeysMatching(f ChainVisitor, r *regexp.Regexp) *Chain

if any of the keys are present, call handler

func (*Chain) IfSection

func (this *Chain) IfSection(key string, visitor Visitor) *Chain

deprecated - use If().

if the sub-section exists, process it

func (*Chain) Must

func (this *Chain) Must(key string, builder ChainVisitor) *Chain

run builder with specified sub-section if section exists, fail otherwise

func (*Chain) OnlyKeys

func (this *Chain) OnlyKeys(allowedKeys ...string) *Chain

func (*Chain) Then

func (this *Chain) Then(fn func()) *Chain

run the specified function as part of the chain

func (*Chain) ThenCheck

func (this *Chain) ThenCheck(fn func() (err error)) *Chain

run the specified checking function as part of the chain

func (*Chain) WarnExtraKeys

func (this *Chain) WarnExtraKeys(allowedKeys ...string) *Chain

type ChainVisitor

type ChainVisitor func(config *Chain) (err error)

ChainVisitor works with Chain.If, Chain.Must, Chain.Each.

type Constructable

type Constructable interface {
	FromConfig(config *Chain) (err error)
}

Constructable works with Chain.Construct, Chain.ConstructFrom, Chain.ConstructIf for things that construct themselves from config.

type FloatValidator

type FloatValidator func(float64) error

use with Section.GetFloat64, Chain.GetFloat64 to validate float

func FloatRange

func FloatRange(min, max float64) FloatValidator

return a range validator for GetInt

type Help

type Help yaml.MapSlice

accumulates ordered help info - see golum.Show

func (*Help) AddSub

func (this *Help) AddSub(title string) (sub *Help)

Start a sub section for this

func (*Help) AsYaml

func (this *Help) AsYaml() (content []byte, err error)

produce the help contents in YAML format

func (*Help) Contains

func (this *Help) Contains(key string) bool

func (*Help) Default

func (this *Help) Default(value any) (rv *Help)

Set default value for this

func (*Help) Get

func (this *Help) Get(key string) (rv any)

func (*Help) GetHelp

func (this *Help) GetHelp(key string) (rv *Help)

func (*Help) Init

func (this *Help) Init(name, note string) (rv *Help)

Initialize the help info, returning a Help to use for parameters

func (*Help) NewItem

func (this *Help) NewItem(name, theType, note string) (rv *Help)

Add an item to the help info

func (*Help) Optional

func (this *Help) Optional() (rv *Help)

Mark this item as optional

func (*Help) Set

func (this *Help) Set(key string, value any) (rv *Help)

Set something on the current help

func (*Help) SetDefault

func (this *Help) SetDefault(value any) (rv *Help)

Set default value for this

func (*Help) SetOptional

func (this *Help) SetOptional() (rv *Help)

Mark this as optional

type Int

type Int interface {
	int | int64 | int32 | int16 | int8
}

type IntValidator

type IntValidator func(int64) error

use with Section.GetInt, Chain.GetInt to validate signed int

func IntAtLeast

func IntAtLeast(min int64) IntValidator

return a validator to error if v not at least min

func IntNonNeg

func IntNonNeg() IntValidator

return a validator to error if v is negative

func IntPos

func IntPos() IntValidator

return a validator to error if v is not positive

func IntPow2

func IntPow2() IntValidator

return a validator to error if v not a power of 2 > 0

func IntRange

func IntRange(min, max int64) IntValidator

return a range validator for GetInt

type Section

type Section struct {
	Context string
	// contains filtered or unexported fields
}

Section represents a config section, and allows access to the settings in the config.

Methods are provided for accessing settings. Many of these methods will perform type coercion. For example, if a setting is provided as a string but is being requested as an int, then the setting will be converted to an int if possible.

The newer Chain API is preferred over this one. To convert a Section to a Chain:

var s *uconfig.Section
chain := s.Chain()...

A Section will typically be provided by the golum lifecycle methods to you, so you don't have to create one in 99% of the cases.

func NewSection

func NewSection(it any) (rv *Section, err error)

create a new Section from nil, /path/to/yaml/file, YAML string, YAML []byte, map[string]any, or map[string]string

func (*Section) Add

func (this *Section) Add(key string, value any)

add a key/value pair to the section

func (*Section) AddProp

func (this *Section) AddProp(key, value string)

add a property to the section. the property will be expanded.

func (*Section) AddProps

func (this *Section) AddProps(props map[string]string)

add the properties to the section. the properties will be expanded.

func (*Section) AnyKeysIn

func (this *Section) AnyKeysIn(keys ...string) bool

return true if any of the listed keys are present

func (*Section) AnyKeysMatch

func (this *Section) AnyKeysMatch(r *regexp.Regexp) bool

return true if any of the keys match

func (*Section) AsResolvedMap

func (this *Section) AsResolvedMap() (rv map[string]any)

dump out the config section as a map, resolving all properties

func (*Section) Chain

func (this *Section) Chain() *Chain

Enable chaining of config calls

func (*Section) CloneProps

func (this *Section) CloneProps() map[string]string

get a copy of the property map

func (*Section) Contains

func (this *Section) Contains(key string) (found bool)

func (*Section) DiffersFrom

func (this *Section) DiffersFrom(that *Section) (differs bool)

compare this section to another one

func (*Section) DumpProps

func (this *Section) DumpProps() (rv string)

func (*Section) DumpVals

func (this *Section) DumpVals() (rv string)

func (*Section) Each

func (this *Section) Each(fn func(key string, val any) error) error

iterate through config items in section, aborting if visitor returns error

func (*Section) EachString

func (this *Section) EachString(fn func(key, val string) error) (err error)

iterate through config items in section, aborting if visitor returns error

func (*Section) Expand

func (this *Section) Expand(text string) string

expand the text using the properties available in this section

func (*Section) ExtraKeys

func (this *Section) ExtraKeys(allowedKeys []string) (rv []string)

return a list of any keys found that are not on allowed list

func (*Section) FailExtraKeys

func (this *Section) FailExtraKeys(allowedKeys ...string)

fail if any other keys are specified in the section than have already been acessed or (if provided) specified in allowedKeys

func (*Section) GetArray

func (this *Section) GetArray(key string, result **Array) (err error)

Get the array or error if it does not exist or is invalid

func (*Section) GetArrayIf

func (this *Section) GetArrayIf(key string, result **Array) (err error)

if key is a Array, set result to it

func (*Section) GetBitRate

func (this *Section) GetBitRate(
	key string,
	result any,
	validators ...IntValidator,
) (err error)

if found, update result with bit rate

SI suffixes such as K, M, G are supported, but Ki, Mi, etc are not.

result must be the address of some sort of signed int.

zero or more validators may be supplied. they take the converted value as an int64. this func will perform basic range checking based on the size of the int after validators are run

handles strings with 0x (hex) or 0 (octal) prefixes

func (*Section) GetBool

func (this *Section) GetBool(key string, result *bool) (err error)

change result to boolean value if found and convertible to bool

func (*Section) GetByteSize

func (this *Section) GetByteSize(
	key string,
	result any,
	validators ...IntValidator,
) (err error)

if found, update result with byte size.

SI suffixes such as K, M, G will be interpreted the same as Ki, Mi, Gi.

result must be the address of some sort of signed int.

zero or more validators may be supplied. they take the converted value as an int64. this func will perform basic range checking based on the size of the int after validators are run

handles strings with 0x (hex) or 0 (octal) prefixes

func (*Section) GetChain

func (this *Section) GetChain(key string) (rv *Chain)

get named subsection as a chain

func (*Section) GetCreateDir

func (this *Section) GetCreateDir(key string, val *string, perm os.FileMode,
) (err error)

Same as GetPath, but also ensures directory exists, creating it if necessary

func (*Section) GetDuration

func (this *Section) GetDuration(key string, val *time.Duration) (err error)

if found, parse to duration and update val

func (*Section) GetFloat64

func (this *Section) GetFloat64(
	key string,
	val *float64,
	validators ...FloatValidator,
) (err error)

if found, parse to float64 and update val

func (*Section) GetInt

func (this *Section) GetInt(
	key string,
	result any,
	validators ...IntValidator,
) (err error)

if found, update result with integral value.

result must be the address of some sort of signed int.

SI suffixes of K, M, G, T are base 1000 multipliers.

SI suffixes of Ki, Mi, Gi, Ti are base 1024 multipliers.

zero or more validators may be supplied. they take the converted value as an int64. this func will perform basic range checking based on the size of the int after validators are run

handles strings with 0x (hex) or 0 (octal) prefixes

func (*Section) GetInts

func (this *Section) GetInts(
	key string,
	result *[]int,
	validators ...IntValidator,
) (err error)

if found, parse into []int and update val

func (*Section) GetIt

func (this *Section) GetIt(key string, value *any)

func (*Section) GetMillis

func (this *Section) GetMillis(
	key string,
	val *int64,
	validators ...IntValidator,
) (
	err error,
)

if found, parse to duration as millis and update val

func (*Section) GetPath

func (this *Section) GetPath(key string, result *string) (err error)

if value is found and a string, then set result to absolute path of value.

otherwise, if value is found but not a string or is blank, then error

func (*Section) GetPosInt

func (this *Section) GetPosInt(key string, result *int) (err error)

same as GetInt, but error if result <= 0

func (*Section) GetRawString

func (this *Section) GetRawString(
	key string,
	result *string,
	validators ...StringValidator,
) (err error)

if found, parse to string and set result without detemplatizing

func (*Section) GetRegexp

func (this *Section) GetRegexp(key string, result **regexp.Regexp) (err error)

get value as regexp

func (*Section) GetRegexpIf

func (this *Section) GetRegexpIf(key string, result **regexp.Regexp) (err error)

if found and not blank, parse to regexp and set result

func (*Section) GetSection

func (this *Section) GetSection(key string, result **Section) (err error)

Get the section or error if it does not exist or is invalid

func (*Section) GetSectionIf

func (this *Section) GetSectionIf(key string, val **Section) (err error)

if key maps to a sub-section, set val to it

func (*Section) GetString

func (this *Section) GetString(
	key string,
	result *string,
	validators ...StringValidator,
) (err error)

if found, parse to string and set result, resolving any templating

func (*Section) GetStringMap

func (this *Section) GetStringMap(key string, val *map[string]string) (err error)

if found, parse into map[string]string and update val

func (*Section) GetStrings

func (this *Section) GetStrings(
	key string,
	result *[]string,
	validators ...StringValidator,
) (err error)

if found, parse into []string and update val

func (*Section) GetStruct

func (this *Section) GetStruct(key string, dst any) (err error)

Get (using JSON conversion) the specified section into dst (a &struct). If key not found, dst is unmodified. May not be super performant, but ok for config type stuff.

func (*Section) GetUInt

func (this *Section) GetUInt(
	key string,
	result any,
	validators ...UIntValidator,
) (err error)

if found, update result with unsigned integral value

result must be the address of some sort of unsigned int

zero or more validators may be supplied. they take the converted value as a uint64. this func will perform basic range checking based on the size of the int after validators are run

handles strings with 0x (hex) or 0 (octal) prefixes handles strings with SI suffixes (G, M, K, Gi, Mi, Ki, ...)

func (*Section) GetUrl

func (this *Section) GetUrl(
	key string,
	result **nurl.URL,
	validators ...StringValidator,
) (err error)

get and parse the url, setting result

func (*Section) GetUrlIf

func (this *Section) GetUrlIf(
	key string,
	result **nurl.URL,
	validators ...StringValidator,
) (err error)

if found and not blank, parse to url and set result

func (*Section) GetValidInt

func (this *Section) GetValidInt(
	key string,
	invalid int,
	result *int,
) (err error)

same as GetInt, but error if result == invalid

func (*Section) GetValidIt

func (this *Section) GetValidIt(key string, value *any) (err error)

func (*Section) GetValidPath

func (this *Section) GetValidPath(key string, result *string) (err error)

same as GetPath, except also errors if unable to stat path

func (*Section) Len

func (this *Section) Len() int

func (*Section) Log

func (this *Section) Log()

output contents to log as YAML

func (*Section) NameContext

func (this *Section) NameContext(key string)

func (*Section) NewChild

func (this *Section) NewChild(it any) (rv *Section, err error)

create a new Section as a child of this one from nil, /path/to/yaml/file, YAML string, YAML []byte, map[string]any, or map[string]string

func (*Section) OnlyKeys

func (this *Section) OnlyKeys(allowedKeys ...string) (err error)

return error if any other keys are specfied in the section than what have already been accessed or (if provided) specified in allowedKeys

func (*Section) Prop

func (this *Section) Prop(key string) string

get the property

func (*Section) Props

func (this *Section) Props() map[string]string

get the property map

func (*Section) StructFromYaml

func (this *Section) StructFromYaml(file string, target any) error

read in the specified yaml file, performing properties on the text, then unmarshal it into target (a ptr to struct)

func (*Section) ToYaml

func (this *Section) ToYaml(file string) error

write contents to yaml file

func (*Section) WarnExtraKeys

func (this *Section) WarnExtraKeys(allowedKeys ...string)

issue a warning if any other keys are specified in the section than have already been acessed or (if provided) specified in allowedKeys

func (*Section) WarnUnknown

func (this *Section) WarnUnknown(h *Help)

issue warnings for any undocumented parameters

func (*Section) Watch

func (this *Section) Watch(
	period time.Duration,
	onChange func(changedFile string) (done bool),
	onError func(err error) (done bool),
)

watch files. if there is a change, then call onChange. if there is an error and onError is set, then call it.

type StringValidator

type StringValidator func(string) error

use with Section.GetString, Chain.GetString to validate string

func StringBlank

func StringBlank() StringValidator

a StringValidator to verify string blank

func StringBlankOr

func StringBlankOr(validator StringValidator) StringValidator

create a StringValidator to verify value is blank or valid

func StringHostOrIp

func StringHostOrIp() StringValidator

create a StringValidator to verify value is an IP or hostname

func StringIp

func StringIp() StringValidator

create a StringValidator to verify value is an IP

func StringLen

func StringLen(min, max int) StringValidator

a StringValidator to verify string length

func StringMatch

func StringMatch(re *regexp.Regexp) StringValidator

a StringValidator to verify string matches regular expression

func StringNotBlank

func StringNotBlank() StringValidator

a StringValidator to verify string not blank

func StringOneOf

func StringOneOf(choices ...string) StringValidator

create a StringValidator to verify value is one of listed

func StringOr

func StringOr(one, other StringValidator) StringValidator

either one or other must be true

func ValidHostPort

func ValidHostPort() StringValidator

return a StringValidator to ensure valid host:port

func ValidHttpUrl

func ValidHttpUrl() StringValidator

return a StringValidator to ensure valid http or https URL

func ValidUrl

func ValidUrl(scheme ...string) StringValidator

return a StringValidator to ensure valid URL with a valid scheme

type UInt

type UInt interface {
	uint | uint64 | uint32 | uint16 | uint8 | uintptr
}

type UIntValidator

type UIntValidator func(uint64) error

use with Section.GetUInt, Chain.GetUInt to validate unsigned int

func UIntRange

func UIntRange(min, max uint64) UIntValidator

return a range validator for GetUInt

type Visitor

type Visitor func(*Section) error

Use with Chain.EachSection, Chain.EachSectionIf, Chain.ASection, Chain.IfSection, Array.Each

type Watch

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

used to watch for changes to files

func (*Watch) Add

func (this *Watch) Add(file string)

add a file to watch

we may get files to add prior to being started

func (*Watch) Start

func (this *Watch) Start(
	period time.Duration,
	onChange func(changedFile string) (done bool),
	onError func(err error) (done bool),
)

watch files. if there is a change, then call onChange. if there is an error and onError is set, then call it.

if either func returns true, then watching will be stopped

func (*Watch) Stop

func (this *Watch) Stop()

stop watching

Jump to

Keyboard shortcuts

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