sconfig – zgo.at/sconfig Index | Examples | Files | Directories

package sconfig

import "zgo.at/sconfig"

Package sconfig is a simple yet functional configuration file parser.

See the README.markdown for an introduction.

Example

Code:play 

package main

import (
	"fmt"
	"net"
	"regexp"

	"zgo.at/sconfig"
	_ "zgo.at/sconfig/handlers/regexp"
)

type Config struct {
	Port    int64
	BaseURL string
	Match   []*regexp.Regexp
	Order   []string
	Hosts   []string
	Address string
}

func main() {
	config := Config{}
	err := sconfig.Parse(&config, "example.config", sconfig.Handlers{
		// Custom handler
		"address": func(line []string) error {
			addr, err := net.LookupHost(line[0])
			if err != nil {
				return err
			}

			config.Address = addr[0]
			return nil
		},
	})
	if err != nil {
		panic(fmt.Errorf("error parsing config: %s", err))
	}

	fmt.Printf("%+v\n", config)

}

Output:

{Port:8080 BaseURL:http://example.com Match:[^foo.+ ^b[ao]r] Order:[allow deny] Hosts:[arp242.net goatcounter.com] Address:arp242.net}

Index

Examples

Functions

func Fields

func Fields(config interface{}) map[string]reflect.Value

Fields gets a list of all fields in a struct. The map key is the name of the field (as it appears in the struct) and the key is the field's reflect.Value (which can be used to set a value).

This is useful if you want to batch operate on a config struct, for example to override from the environment or flags.

func FindConfig

func FindConfig(file string) string

FindConfig tries to find a configuration file at the usual locations.

The following paths are checked (in this order):

$XDG_CONFIG/<file>
$HOME/.<file>
/etc/<file>
/usr/local/etc/<file>
/usr/pkg/etc/<file>
./<file>

The default for $XDG_CONFIG is $HOME/.config if it's not set.

func MustParse

func MustParse(c interface{}, file string, handlers Handlers)

MustParse behaves like Parse(), but panics if there is an error.

func Parse

func Parse(config interface{}, file string, handlers Handlers) (returnErr error)

Parse reads the file from disk and populates the given config struct.

A line is matched with a struct field by "camelizing" the first word. For example "key-name" becomes "KeyName". You can also use the plural ("KeyNames") as the field name.

sconfig will attempt to set the field from the passed Handlers map (see below), a configured type handler, or the encoding.TextUnmarshaler interface, in that order.

The Handlers map, which may be nil, can be given to customize the behaviour for individual configuration keys. This will override the type handler (if any). The function is expected to set any settings on the struct; for example:

Parse(&config, "config", Handlers{
    "SpecialBool": func(line []string) error {
        if line[0] == "yup!" {
            config.Bool = true
        }
        return nil
     },
})

Will allow you to do:

special-bool yup!

func RegisterType

func RegisterType(typ string, fun ...TypeHandler)

RegisterType sets the type handler functions for a type. Existing handlers are always overridden (it doesn't add to the list!)

The handlers are chained; the return value is passed to the next one. The chain is stopped if one handler returns a non-nil error. This is particularly useful for validation (see ValidateSingleValue() and ValidateValueLimit() for examples).

Types

type Handler

type Handler func([]string) error

Handler functions can be used to run special code for a field. The function takes the unprocessed line split by whitespace and with the option name removed.

type Handlers

type Handlers map[string]Handler

Handlers can be used to run special code for a field. The map key is the name of the field in the struct.

type TypeHandler

type TypeHandler func([]string) (interface{}, error)

TypeHandler takes the field to set and the value to set it to. It is expected to return the value to set it to.

func ValidateNoValue

func ValidateNoValue() TypeHandler

ValidateNoValue returns a type handler that will return an error if there are any values.

func ValidateSingleValue

func ValidateSingleValue() TypeHandler

ValidateSingleValue returns a type handler that will return an error if there is more than one value or if there are no values.

func ValidateValueLimit

func ValidateValueLimit(min, max int) TypeHandler

ValidateValueLimit returns a type handler that will return an error if there either more values than max, or fewer values than min.

Source Files

handlers.go inflect.go sconfig.go validate.go

Directories

PathSynopsis
handlersPackage handlers contains handlers that require extra imports (either from the standard library, or third-party packages).
handlers/bigPackage big contains handlers for parsing values with the math/big package.
handlers/html
handlers/html/templatePackage template contains handlers for parsing values with the html/template package.
handlers/netPackage net contains handlers for parsing values with the net package.
handlers/net/urlPackage url contains handlers for parsing values with the net/url package.
handlers/regexpPackage regexp contains handlers for parsing values with the regexp package.
Version
v1.2.2 (latest)
Published
Oct 19, 2022
Platform
linux/amd64
Imports
11 packages
Last checked
1 day ago

Tools for package owners.