conf

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2021 License: MIT Imports: 7 Imported by: 3

README

module conf

go get github.com/dmfed/conf to download.

import "github.com/dmfed/conf" to use in your code.

Module conf implements a very simple config parser with two types of values: key value pairs and single word options. Each of these must be put on separate line in a file like this:

key1 = value
key2 = value1, value2, value3
option1
option2

Values can also be read from any io.Reader or io.ReadCloser

Typical use case would look like this:

config, err := conf.ParseFile("filename")
if err != nil {
  // Means we failed to read from file
  // config variable is now nil and unusable
}

value, err := config.GetSetting("mykey").Float64()
if err != nil {
  // Means that value has not been found
  // or can not be cast to desired type
}
// value now holds float64.

value2, _ := config.GetSetting("otherkey").String()
// value2 now holds string if "otherkey" was parsed, else an empty string.
// Trying to extract non existing value will always return default value for
// the type.

See description of module's types and methods which are quite self-explanatory.

See also https://pkg.go.dev/github.com/dmfed/conf for a complete description of module's functions.

Below is listing of a working example of a program parsing config (also found example/main.go in the repository)

package main

import (
	"bytes"
	"fmt"

	"github.com/dmfed/conf"
)

var testConf = []byte(`
# commented
port=10000
servers = 10.0.0.1, 10.0.0.2, 10.0.0.3
bool0=0
booltrue = true
distance=13.42
color`)

func main() {
	r := bytes.NewReader(testConf) // creating io.Reader from []byte()
	config := conf.ParseReader(r)  // we could call conf.ParseFile("filename") here

	// First of all we can access parsed values directly:
	for key, value := range config.Settings {
		fmt.Println(key, value)
	}
	for opt := range config.Options {
		fmt.Println(opt)
	}
	fmt.Println()

	// GetSetting(key string) returns instance of Setting:
	// type Setting struct {
	//    Key     string  // requested key
	//    Value   string  // value if found
	//    Found   bool    // true if requested key-value pair was found else false
	// }
	port := config.GetSetting("port")
	fmt.Printf("variable port has type: %T\nport.Key == %v, port.Value == %v, port.Found == %v\n", port, port.Key, port.Value, port.Found)

	// We can cast Setting.Value to a desired type including int, float64,
	// bool and string. If requested Setting was not found trying to extract
	// its value will return an error.
	// Method below will return error if "port = somevalue" was not in config
	// file or if conversion to int fails.
	n, _ := port.Int()
	fmt.Printf("n has value: %v, type: %T\n", n, n)

	// Split() method gets comma separated values from key-value pair:
	//    key = value1, value2, value3
	// and retuns slice of []Setting. It will be empty if requested key
	// was not found and will have only one element if values were not actually
	// comma separated. Note that Split() never returns nil.
	servers := config.GetSetting("servers").Split()
	fmt.Println("Found servers:")
	for i, s := range servers {
		ip, _ := s.String()
		fmt.Println(i+1, "\t", ip)
	}

	if config.HasOption("color") {
		fmt.Println("Hooray, we've found option \"color\"!")
		// do something useful
	}

	distance, _ := config.GetSetting("distance").Float64()
	fmt.Printf("distance has value: %v, type: %T\n\n", distance, distance)

	var t, f bool
	t, _ = config.GetSetting("booltrue").Bool()

	// We can also check if key-value pair exists prior to
	// actually trying to get it.
	if config.HasSetting("bool0") {
		f, _ = config.GetSetting("bool0").Bool()
	}
	fmt.Printf("t's type is: %T, value: %v, f's type is: %T, value: %v\n\n", t, t, f, f)

	_, err := config.GetSetting("commented").String()
	fmt.Printf("Commented out string \"# commented\" does not appear in Config.\nTrying to extract value will return error: %v", err)
}

Here is the full output of the above code:

port 10000
servers 10.0.0.1, 10.0.0.2, 10.0.0.3
bool0 0
booltrue true
distance 13.42
color

variable port has type: conf.Setting
port.Key == port, port.Value == 10000, port.Found == true
n has value: 10000, type: int
Found servers:
1 	 10.0.0.1
2 	 10.0.0.2
3 	 10.0.0.3
Hooray, we've found option "color"!
distance has value: 13.42, type: float64

t's type is: bool, value: true, f's type is: bool, value: false

Commented out string "# commented" does not appear in Config.
Trying to extract value will return error: key was not found

Documentation

Overview

module conf

import "github.com/dmfed/conf"

Module conf implements a very simple config parser with two types of values: key value pairs and single word options. Each of these must be put on separate line in a file like this:

key1 = value
key2 = value1, value2, value3
option1
option2

Values can also be read from any io.Reader or io.ReadCloser

Typical use case would look like this:

config, err := conf.ParseFile("filename")
if err != nil {
	// Means we failed to read from file
	// config variable is now nil and unusable
}
value, err := config.GetSetting("mykey").Float64()
if err != nil {
	// Means that value has not been found
	// or can not be cast to desired type
}
// value now holds float64.

value2, _ := config.GetSetting("otherkey").String()
// value2 now holds string if "otherkey" was parsed, else an empty string.

Trying to extract non existing value will always return default value for the type.

See description of module's types and methods which are quite self-explanatory.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when trying to get empty value from Setting.
	ErrNotFound = errors.New("key was not found")
	// ErrParsingBool is returned when Setting.Bool() method is called and Setting.Value
	// can not be interpreted as boolean.
	ErrParsingBool = errors.New("value can not be interpreted as bool")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// Settings store key value pairs ("key = value" in config file)
	// all key value pairs found when parsing input are accumulated in this map.
	Settings map[string]string
	// Options map stores single word options ("option" in config file)
	Options map[string]struct{}
}

Config holds parsed keys and values. Settings and Options can be accessed with Config.Settings and Config.Options maps directly.

func ParseFile

func ParseFile(filename string) (*Config, error)

ParseFile reads values from file. It returns nil and error if os.Open(filename) fails. It would be wise to always check returned error. ParseFile captures two types of values: "key = value" and "option". Either key value pair or option must be put in its own line in the file. Key or option must be a single word. In example line:

"option1 option2"

only option1 will be captured. option2 needs to be in a separate line in the file to take effect. In line "key = value1,value2,value3" all of value1, value2, and value3 will be captured. They can be later accesed separately with Setting's Split() method.

func ParseReadCloser added in v0.2.1

func ParseReadCloser(r io.ReadCloser) *Config

ParseReadCloser reads from r, returns Config and calls r.Close(). See also ParseFile.

func ParseReader

func ParseReader(r io.Reader) *Config

ParseReader reads from r and returns Config. See also ParseFile.

func (*Config) GetSetting added in v0.2.1

func (c *Config) GetSetting(key string) (s Setting)

Get returns a Setting. If key was not found the returned Setting's Value will be empty string and Setting's Found field will be set to false

func (*Config) HasOption added in v0.2.1

func (c *Config) HasOption(option string) (exists bool)

HasOption returns true if line:

"key"

was found in the parsed file

func (*Config) HasSetting added in v0.2.1

func (c *Config) HasSetting(key string) (exists bool)

HasSetting returns true if line:

"key = somevalue"

was found in the parsed data

type Setting added in v0.2.1

type Setting struct {
	// Key holds the name of key parsed from the configuration
	Key string
	// Value holds the value of key parsed from the configuration
	Value string
	// Found is set to true if Key was found in the parsed config, false otherwise
	Found bool
}

Setting represents key-value pair read from config file

func (Setting) Bool added in v0.2.1

func (st Setting) Bool() (bool, error)

Bool tries to interpret Setting's Value as bool "1", "true", "yes" (case insensitive) yields true "0", "false", "no" (case insensitive) yields false

func (Setting) Float64 added in v0.2.1

func (st Setting) Float64() (float64, error)

Float64 converts Setting's Value to float64 if possible If setting's key was not found in the config this method will return ErrNotFound

func (Setting) Int added in v0.2.1

func (st Setting) Int() (int, error)

Int converts Setting's Value to int if possible If setting's key was not found in the config this method will return ErrNotFound

func (Setting) Split added in v0.2.1

func (st Setting) Split() []Setting

Split splits Setting's value with separator sep and returns []Setting. If separator was not found the method returns slice with only one Setting. This method is intended for use when config file has comma separated values like:

myoption = first,second,third

Split(",") will return slice with 3 separate Setting each holding one of "first, second, third" in their Value fields.

func (Setting) String added in v0.2.1

func (st Setting) String() (string, error)

String returns option Value as string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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