config

package module
v0.0.0-...-ea660d6 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2014 License: MIT Imports: 13 Imported by: 0

README

Configuration File Parser for Go

Syntax

Parser supports a subset of TOML v0.2.0 syntax.

Main differences are:

  • section and option names are case insensitive;
  • sub-sections are not supported;
  • multi-dimensional arrays are not supported;
  • tables are not supported; and
  • array of tables are not supported.

Why? I just don't need multi-dimensional arrays or tables in my configuration files.

Parser implements following grammar (EBNF style):

	config = section | options
	section = '[' IDENTIFIER ']' EOL options
	options = option {option}
	option =  IDENTIFIER '=' (value | array) EOL
	value = BOOL | INT | FLOAT | DATE | STRING
	array = '[' {EOF} value {EOF} {, {EOF} value} {EOF} ']'

Parser can load as many configurations as you want, and each load can update existing options.

Installation

go get github.com/cbonello/gp-config

Testing

gp-config uses gocheck for testing.

To install gocheck, just run the following command:

go get launchpad.net/gocheck

To run the test suite, use the following command:

go test github.com/cbonello/gp-config -v

You can also check test coverage if you're using go 1.2 or later:

go test github.com/cbonello/gp-config -v -coverprofile=test.out
go tool cover -html=test.out

Usage

Loading Configuration Files

Configuration can either be stored in a string or a file.

import (
	"flag"
	"fmt"
	"github.com/cbonello/gp-config"
	"os"
)
const deflt = `version = [1, 0, 10]
			   [database]
				   dbname = "mydb"
				   user = "foo"
				   password = "bar"`
var dev bool = false
func main() {
	flag.BoolVar(&dev, "dev", false, "Runs application in debug mode, default is production.")
	flag.Parse()
	// Set default options (Production mode).
	cfg := config.NewConfiguration()
	if err := cfg.LoadString(deflt); err != nil {
		fmt.Printf("error: default config: %d:%d: %s\n",
			err.Line, err.Column, err)
		os.Exit(1)
	}
	if dev {
		// Override default options with debug mode settings.
		if err := cfg.LoadFile("debug.cfg"); err != nil {
			fmt.Printf("error: %s: %d:%d: %s\n",
				err.Filename, err.Line, err.Column, err)
			os.Exit(1)
		}
	}
	...
}

Contents of debug.cfg may for instance be:

[database]
	dbname = "mydb_test"
Reading Configuration Files
Basic API
	if dbname, err := cfg.GetString("database.dbname"); err != nil {
		fmt.Printf("error: configuration: missing database name\n")
		os.Exit(1)
	}
	user := cfg.GetStringDefault("database.dbname", "user")
	password := cfg.GetStringDefault("database.dbname", "foobar")

See examples/demo/ for a complete demo application.

Full API documentation is available at godoc.org.

Reflection API

Following structure may be declared to record options of [database] section defined above.

	type database struct {
		Name     string `option:"dbname"`
		Username string `option:"user"`
		Password string
	}

A structure field annotation may be used if there is no direct match between a field name and an option name.

And finally, to decode:

	var db database
	if err := cfg.Decode("database", &db); err != nil {
		fmt.Println("error:", err)
		os.Exit(1)
	}

See examples/demo-decode/ for a complete demo application.

Full API documentation is available at godoc.org.

Examples

Demo applications are provided in the examples/ directory. To launch them:

go run github.com/cbonello/gp-config/examples/demo/demo.go
go run github.com/cbonello/gp-config/examples/demo-decode/demo.go

Documentation

Index

Constants

View Source
const (
	TkEOF        kind = iota // End-of-file token.
	TkEOL                    // End-of-line token.
	TkError                  // An error occurred; value is error message.
	TkIdentifier             // Identifier token.
	TkBool                   // Boolean.
	TkString                 // A string (does not include double quotes).
	TkInt                    // An integer.
	TkFloat                  // A floating point number.
	TkDate                   // A date.
	TkEqual                  // '='.
	TkLBracket               // '['.
	TkRBracket               // ']'.
	TkComma                  // ','.

)

Tokens returned by lexer.

Variables

This section is empty.

Functions

func NewLexer

func NewLexer(filename, contents string) *lexer

NewLexer instanciates a new lexer.

Types

type Configuration

type Configuration struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Configuration context.

func NewConfiguration

func NewConfiguration() (c *Configuration)

NewConfiguration creates a new configuration context.

func (*Configuration) Decode

func (c *Configuration) Decode(section string, structPtr interface{}) (err error)

Decode initializes structPtr with contents of given section. Function does not support circular types; it will loop forever.

func (*Configuration) Get

func (c *Configuration) Get(option string) (interface{}, error)

Get returns the value (scalar or array) associated with given option name, or nil if option is undefined. option is a dot-separated path (e.g. section.option).

func (*Configuration) GetBool

func (c *Configuration) GetBool(option string) (bool, error)

GetBool returns the boolean value associated with given option name. An error is flagged if option does not record a boolean value or it is undefined.

func (*Configuration) GetBoolArray

func (c *Configuration) GetBoolArray(option string) ([]bool, error)

GetBoolArray returns the array of booleans associated with given option name. An error is flagged if option does not record an array of booleans or it is undefined.

func (*Configuration) GetBoolArrayDefault

func (c *Configuration) GetBoolArrayDefault(option string, dfault []bool) []bool

GetBoolArrayDefault is similar to GetBoolArray but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetBoolDefault

func (c *Configuration) GetBoolDefault(option string, dfault bool) bool

GetBoolDefault is similar to GetBool but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetDate

func (c *Configuration) GetDate(option string) (time.Time, error)

GetDate returns the date associated with given option name. An error is flagged if option does not record a date or it is undefined.

func (*Configuration) GetDateArray

func (c *Configuration) GetDateArray(option string) ([]time.Time, error)

GetDateArray returns the array of dates associated with given option name. An error is flagged if option does not record an array of dates or it is undefined.

func (*Configuration) GetDateArrayDefault

func (c *Configuration) GetDateArrayDefault(option string, dfault []time.Time) []time.Time

GetDateArrayDefault is similar to GetDateArray but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetDateDefault

func (c *Configuration) GetDateDefault(option string, dfault time.Time) time.Time

GetDateDefault is similar to GetDate but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetFloat

func (c *Configuration) GetFloat(option string) (float64, error)

GetFloat returns the floating-point number associated with given option name. An error is flagged if option does not record a floating-point number or it is undefined.

func (*Configuration) GetFloatArray

func (c *Configuration) GetFloatArray(option string) ([]float64, error)

GetFloatArray returns the array of floating-point values associated with given option name. An error is flagged if option does not record an array of floating-point values or it is undefined.

func (*Configuration) GetFloatArrayDefault

func (c *Configuration) GetFloatArrayDefault(option string, dfault []float64) []float64

GetFloatArrayDefault is similar to GetFloatArray but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetFloatDefault

func (c *Configuration) GetFloatDefault(option string, dfault float64) float64

GetFloatDefault is similar to GetFloat but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetInt

func (c *Configuration) GetInt(option string) (int64, error)

GetInt returns the integer associated with given option name. An error is flagged if option does not record an integer or it is undefined.

func (*Configuration) GetIntArray

func (c *Configuration) GetIntArray(option string) ([]int64, error)

GetIntArray returns the array of integers associated with given option name. An error is flagged if option does not record an array of integers or it is undefined.

func (*Configuration) GetIntArrayDefault

func (c *Configuration) GetIntArrayDefault(option string, dfault []int64) []int64

GetIntArrayDefault is similar to GetIntArray but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetIntDefault

func (c *Configuration) GetIntDefault(option string, dfault int64) int64

GetIntDefault is similar to GetInt but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetString

func (c *Configuration) GetString(option string) (string, error)

GetString returns the string associated with given option name. An error is flagged if option does not record a string or it is undefined.

func (*Configuration) GetStringArray

func (c *Configuration) GetStringArray(option string) ([]string, error)

GetStringArray returns the array of strings associated with given option name. An error is flagged if option does not record an array of strings or it is undefined.

func (*Configuration) GetStringArrayDefault

func (c *Configuration) GetStringArrayDefault(option string, dfault []string) []string

GetStringArrayDefault is similar to GetStringArray but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) GetStringDefault

func (c *Configuration) GetStringDefault(option string, dfault string) string

GetStringDefault is similar to GetString but given default value is returned if option does not exist or is of wrong type.

func (*Configuration) HasOption

func (c *Configuration) HasOption(option string) (result bool)

HasOption returns true if given option is defined, false otherwise.

func (*Configuration) IsSection

func (c *Configuration) IsSection(section string) bool

IsSection returns true if given section exists, otherwise false.

func (*Configuration) Len

func (c *Configuration) Len() (length int)

Len returns the number of options defined.

func (*Configuration) LoadFile

func (c *Configuration) LoadFile(filename string) (err *ConfigurationError)

LoadFile loads the configuration stored in given file.

func (*Configuration) LoadString

func (c *Configuration) LoadString(contents string) (err *ConfigurationError)

LoadString loads the configuration stored in given string.

func (*Configuration) Options

func (c *Configuration) Options(section string) (options []string)

Options returns the options defined in given section sorted in ascending order. Optionsglobally defined are returned if given section is an empty string.

func (*Configuration) Sections

func (c *Configuration) Sections() (sections []string)

Sections returns the sections defined sorted in ascending order.

func (*Configuration) String

func (c *Configuration) String() string

String dumps a configuration to a string.

type ConfigurationError

type ConfigurationError struct {
	Filename     string // Filename.
	Line, Column int    // Line and column.
	// contains filtered or unexported fields
}

ConfigurationError records parsing errors.

func (*ConfigurationError) Error

func (c *ConfigurationError) Error() string

Error dumps a configuration-error to a string.

type Parser

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

Parser context.

func NewParser

func NewParser(filename string) (*Parser, error)

NewParser instanciates a parser for given configuration file.

func NewStringParser

func NewStringParser(contents string) *Parser

NewStringParser instanciates a parser for given configuration string.

func (*Parser) Parse

func (p *Parser) Parse(c *Configuration) (err *ConfigurationError)

Parse parses a configuration stored either in a file or a string.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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