ini

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2023 License: MIT Imports: 8 Imported by: 3

README

PkgGoDev Go Report Card

go-ini

A Go package that encodes and decodes INI-files.

Usage

data := `[settings]
username=root
password=swordfish
shell[unix]=/bin/sh
shell[win32]=PowerShell.exe
`

var config struct {
    Settings struct {
        Username string            `ini:"username"`
        Password string            `ini:"password"`
        Shell    map[string]string `ini:"shell"`
    } `ini:"settings"`
}

if err := ini.Unmarshal(data, &config); err != nil {
    fmt.Println(err)
}
fmt.Println(config)

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal

func Marshal(v interface{}) ([]byte, error)

Marshal returns the INI encoding of v.

Marshal traverses the value of v recursively. If an encountered value implements the encoding.MarshalText interface, Marshal calls its MarshalText method and encodes the result into the INI property value. Otherwise Marshal attempts to encode a textual representation of the value through string formatting.

The following types are encoded:

Struct values are encoded as INI sections. Each exported struct field becomes a property of the section, using the field name as the property key, unless the field is omitted for one of the reasons given below. The field value encodes as the property value according to the rules given below.

The encoding of each struct field can be customized by the format string stored under the "ini" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

The "omitempty" option specifies that the field should be omitted from the encoding if the field is an empty value, defined as false, 0, a nil pointer, a nil interface value, and an empty string.

As a special case, if the field tag is "-", the field is always omitted.

Examples of struct field tags and their meanings:

// Field appears in INI as key "myName".
Field int `ini:"myName"`

// Field is ignored by this package.
Field int `ini:"-"`

Boolean values encode as the string literal "true" or "false".

Floating point, integer and Number values encoded as string representations.

String values encode as valid UTF-8 strings.

Pointer values encode as the value pointed to. A nil pointer encodes as an empty property value.

Interface values encode as the value contained in the interface. A nil interface value encodes as an empty property value.

Slices and arrays are encoded as a sequential list of properties with duplicate keys.

Structs are encoded as a string, the value of which is derived from the encoding.TextMarshaler interface. A struct that does not implement this interface causes Marshal to return a MarshalTypeError.

Channel, complex, map and function values cannot be encoded in INI. Attempting to encode such a value causes Marshal to return a MarshalTypeError.

Example
type Database struct {
	Server string
	Port   int
	File   string
	Path   map[string]string
}

type Person struct {
	Name         string
	Organization string
}

type Config struct {
	Version  string
	Owner    Person
	Database Database
}

config := Config{
	Version: "1.2.3",
	Owner: Person{
		Name:         "John Doe",
		Organization: "Acme Widgets Inc.",
	},
	Database: Database{
		Server: "192.0.2.62",
		Port:   143,
		File:   "payroll.dat",
		Path:   map[string]string{"unix": "/var/db"},
	},
}

b, err := ini.Marshal(config)
if err != nil {
	fmt.Println("error:", err)
}
os.Stdout.Write(b)
Output:

Version=1.2.3

[Owner]
Name=John Doe
Organization=Acme Widgets Inc.

[Database]
Server=192.0.2.62
Port=143
File=payroll.dat
Path[unix]=/var/db

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses the INI-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer to a struct, Unmarshal returns an UnmarshalTypeError; INI-encoded data must be encoded into a struct.

Unmarshal uses the inverse of the encodings that Marshal uses, following the rules below:

So-called "global" property keys are matched to a struct field within v, either by its field name or tag. Values are then decoded according to the type of the destination field.

Sections must be unmarshaled into a struct. Unmarshal matches the section name to a struct field name or tag. Subsequent property keys are then matched against struct field names or tags within the struct.

If a duplicate section name or property key is encountered, Unmarshal will allocate a slice according to the number of duplicate keys found, and append each value to the slice. If the destination struct field is not a slice type, an error is returned.

A struct field tag name may be a single asterisk (colloquially known as the "wildcard" character). If such a tag is detected and the destination field is a slice of structs, all sections are decoded into the destination field as an element in the slice. If a struct field named "ININame" is encountered, the section name decoded into that field.

A struct field may be declared as a pointer to a type. If this is the case, the field's value is set to nil if no such key name is found in the INI-encoded data.

Example
type Database struct {
	Server string
	Port   int
	File   string
	Path   map[string]string
}

type Person struct {
	Name         string
	Organization string
}

type Config struct {
	Version  string
	Owner    Person
	Database Database
}

var config Config

data := []byte(`Version=1.2.3

	[Owner]
	Name=John Doe
	Organization=Acme Widgets Inc.
	
	[Database]
	Server=192.0.2.62
	Port=143
	File=payroll.dat
	Path[unix]=/var/db
	Path[win32]=C:\db`)

if err := ini.Unmarshal(data, &config); err != nil {
	fmt.Println("error:", err)
}
fmt.Println(config)
Output:

{1.2.3 {John Doe Acme Widgets Inc.} {192.0.2.62 143 payroll.dat map[unix:/var/db win32:C:\db]}}

func UnmarshalWithOptions

func UnmarshalWithOptions(data []byte, v interface{}, opts Options) error

UnmarshalWithOptions allows parsing behavior to be configured with an Options value.

Types

type DecodeError added in v0.1.4

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

A DecodeError describes an error that was encountered while parsing a value to a specific Go type.

func (DecodeError) Error added in v0.1.4

func (e DecodeError) Error() string

type MarshalTypeError

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

A MarshalTypeError represents a type that cannot be encoded in an INI-compatible textual format.

func (*MarshalTypeError) Error

func (e *MarshalTypeError) Error() string

type MarshalerError

type MarshalerError struct {
	Type reflect.Type
	Err  error
}

A MarshalerError represents an error from calling a MarshalText method.

func (*MarshalerError) Error

func (e *MarshalerError) Error() string

type Options

type Options struct {
	// AllowMultilineValues enables a property value to contain multiple lines.
	// Currently supported methods:
	//
	// - Escaped newlines: A newline character preceded by a single backslash
	// - Space-prefixed: A line beginning with one or more spaces
	AllowMultilineValues bool

	// AllowNumberSignComments treats lines beginning with the number sign (#)
	// as a comment.
	AllowNumberSignComments bool

	// AllowEmptyValues permits a key to have an empty assignment.
	AllowEmptyValues bool
}

The Options type is used to configure the behavior during unmarshalling.

type UnmarshalTypeError

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

An UnmarshalTypeError describes a value that was not appropriate for a value of a specific Go type.

func (*UnmarshalTypeError) Error

func (e *UnmarshalTypeError) Error() string

Jump to

Keyboard shortcuts

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