confkey

package
v0.29.4 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package confkey looks for tags on a structure and set values based on the tag rather than the struct item names

Features

Defaults are supported and can be fetched from the shell environment

The tags can specify some formating like comma splits and other commonly seen patterns in config files.

Conversion of []string, ints, strings, time.Duration and booleans are support

Validations can be done on a struct basis using the github.com/choria-io/go-validators package

A sample structure might look like this, the package contains utilities to set values, apply defaults and perform validations

type Config struct {
    Loglevel string        `confkey:"loglevel" default:"warn" validate:"enum=debug,info,warn,error"`
    Mode     string        `confkey:"mode" default:"server" validate:"enum=server,client"`
    Servers  []string      `confkey:"servers" type:"comma_split" environment:"SERVERS"`
    Path     []string      `confkey:"path" type:"path_split" default:"/bin:/usr/bin"`
    I        time.Duration `confkey:"interval" type:"duration" default:"1h"`
}

The utilities here will let you parse any config file that might have keys like loglevel etc and map the string values read from the text file onto the structure

Example (Basic)
package main

import (
	"fmt"
	"os"
	"strings"

	confkey "github.com/choria-io/go-choria/confkey"
)

type Config struct {
	Loglevel string   `confkey:"loglevel" default:"warn" validate:"enum=debug,info,warn,error"`
	Mode     string   `confkey:"mode" default:"server" validate:"enum=server,client"`
	Servers  []string `confkey:"servers" type:"comma_split" environment:"SERVERS"`
	Path     []string `confkey:"path" type:"colon_split" default:"/bin:/usr/bin"` // can also be path_split to be OS aware
}

func main() {
	c := &Config{}

	err := confkey.SetStructDefaults(c)
	if err != nil {
		panic(err)
	}

	fmt.Println("Defaults:")
	fmt.Printf("  loglevel: %s\n", c.Loglevel)
	fmt.Printf("  mode: %s\n", c.Mode)
	fmt.Printf("  path: %s\n", strings.Join(c.Path, ","))
	fmt.Println("")

	// here you would read your config file, but lets just fake it
	// and set specific values

	// every call to SetStructFieldWithKey validates what gets set
	err = confkey.SetStructFieldWithKey(c, "loglevel", "error")
	if err != nil {
		panic(err)
	}

	err = confkey.SetStructFieldWithKey(c, "mode", "client")
	if err != nil {
		panic(err)
	}

	// even though we are setting it, if the ENV is set it overrides
	os.Setenv("SERVERS", "s1:1024, s2:1024")
	err = confkey.SetStructFieldWithKey(c, "servers", "s:1024")
	if err != nil {
		panic(err)
	}

	fmt.Println("Loaded:")
	fmt.Printf("  loglevel: %s\n", c.Loglevel)
	fmt.Printf("  mode: %s\n", c.Mode)
	fmt.Printf("  servers: %s\n", strings.Join(c.Servers, ","))
	fmt.Println("")

	// getting a string by name
	fmt.Println("Retrieved:")
	fmt.Printf("  loglevel: %s\n", confkey.StringFieldWithKey(c, "loglevel"))
	fmt.Printf("  servers: %s\n", strings.Join(confkey.StringListWithKey(c, "servers"), ","))
	fmt.Println("")

	// but you can also validate the entire struct if you like, perhaps you
	// set some stuff directly to its fields
	err = confkey.Validate(c)
	if err != nil {
		fmt.Printf("invalid: %s\n", err)
		panic(err)
	}

	fmt.Println("valid")

	// setting a specific bad value yields an error
	err = confkey.SetStructFieldWithKey(c, "loglevel", "fail")
	if err != nil {
		fmt.Printf("invalid: %s\n", err)
	}

}
Output:

Defaults:
  loglevel: warn
  mode: server
  path: /bin,/usr/bin

Loaded:
  loglevel: error
  mode: client
  servers: s1:1024,s2:1024

Retrieved:
  loglevel: error
  servers: s1:1024,s2:1024

valid
invalid: Loglevel enum validation failed: 'fail' is not in the allowed list: debug, info, warn, error

Index

Examples

Constants

This section is empty.

Variables

View Source
var Undocumented = "Undocumented"

Functions

func BoolWithKey

func BoolWithKey(target any, key string) bool

BoolWithKey retrieves a bool from target that matches key, false when not found

func DefaultString

func DefaultString(target any, key string) (string, bool)

DefaultString retrieves the default for a field

func Description

func Description(target any, key string) (string, bool)

Description retrieves the description tag from a key in target

func Environment

func Environment(target any, key string) (string, bool)

Environment retrieves the environment variable used to set a value

func FieldWithKey

func FieldWithKey(target any, key string) (string, error)

FieldWithKey determines the struct key name that is tagged with a certain confkey

func FindFields

func FindFields(target any, re string) ([]string, error)

FindFields looks for fields matching regular expression re and return their keys

func Int64WithKey

func Int64WithKey(target any, key string) int64

Int64WithKey retrieves an int from target that matches key, 0 when not found

func IntWithKey

func IntWithKey(target any, key string) int

IntWithKey retrieves an int from target that matches key, 0 when not found

func InterfaceWithKey added in v0.20.0

func InterfaceWithKey(target any, key string) (any, bool)

InterfaceWithKey retrieves the value from target that matches key as an any

func IsDeprecated

func IsDeprecated(target any, key string) (bool, bool)

IsDeprecated determines if the key is set to be deprecated on target

func KeyTag

func KeyTag(target any, key string, tag string) (string, bool)

KeyTag retrieves a specific tag from a field with key on target

func SetStructDefaults

func SetStructDefaults(target any) error

SetStructDefaults extract defaults out of the tags and set them to the key

func SetStructFieldWithKey

func SetStructFieldWithKey(target any, key string, value any) error

SetStructFieldWithKey finds the struct key that matches the confkey on target and assign the value to it

func StringFieldWithKey

func StringFieldWithKey(target any, key string) string

StringFieldWithKey retrieves a string from target that matches key, "" when not found

func StringListWithKey

func StringListWithKey(target any, key string) []string

StringListWithKey retrieves a []string from target that matches key, empty when not found

func Tag

func Tag(s any, field string, tag string) (string, bool)

Tag retrieve a tag for a struct field

func Type

func Type(target any, key string) (string, bool)

Type returns the type for a field as a string, target has to be a pointer

func URL

func URL(target any, key string) (string, bool)

URL retrieves the url for additional docs for a key

func Validate

func Validate(target any) error

Validate validates the struct

func Validation

func Validation(target any, key string) (string, bool)

Validation retrieves the validation configuration, empty when unvalidated

Types

type Doc

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

func KeyDoc

func KeyDoc(target any, key string, container string) *Doc

KeyDoc constructs a Doc for key within target, marked up to be within container

func (*Doc) ConfigKey

func (d *Doc) ConfigKey() string

ConfigKey is the key to place within the configuration to set the item

func (*Doc) Default

func (d *Doc) Default() string

Default is the default value as a string

func (*Doc) Deprecate

func (d *Doc) Deprecate() bool

Deprecated indicates if the item is not in use anymore

func (*Doc) Description

func (d *Doc) Description() string

Description is a description of the item, empty when not set

func (*Doc) Environment

func (d *Doc) Environment() string

Environment is an environment variable that can set this item, empty when not settable

func (*Doc) SetDescription

func (d *Doc) SetDescription(desc string)

SetDescription overrides the description of the key

func (*Doc) StructKey

func (d *Doc) StructKey() string

StructKey is the key within the structure to lookup to retrieve the item

func (*Doc) Type

func (d *Doc) Type() string

Type is the type of data to store in the item

func (*Doc) URL

func (d *Doc) URL() string

URL returns a url that describes the related feature in more detail

func (*Doc) Validation

func (d *Doc) Validation() string

Validation is the configured validation

Jump to

Keyboard shortcuts

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