toml

package module
v1.9.5 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2022 License: Apache-2.0, MIT Imports: 15 Imported by: 3,025

README

go-toml

Go library for the TOML format.

This library supports TOML version v1.0.0-rc.3

Go Reference license Build Status codecov Go Report Card FOSSA Status

Development status

ℹ️ Consider go-toml v2!

The next version of go-toml is in active development, and nearing completion.

Though technically in beta, v2 is already more tested, fixes bugs, and much faster. If you only need reading and writing TOML documents (majority of cases), those features are implemented and the API unlikely to change.

The remaining features will be added shortly. While pull-requests are welcome on v1, no active development is expected on it. When v2.0.0 is released, v1 will be deprecated.

👉 go-toml v2

Features

Go-toml provides the following features for using data parsed from TOML documents:

  • Load TOML documents from files and string data
  • Easily navigate TOML structure using Tree
  • Marshaling and unmarshaling to and from data structures
  • Line & column position data for all parsed elements
  • Query support similar to JSON-Path
  • Syntax errors contain line and column numbers

Import

import "github.com/pelletier/go-toml"

Usage example

Read a TOML document:

config, _ := toml.Load(`
[postgres]
user = "pelletier"
password = "mypassword"`)
// retrieve data directly
user := config.Get("postgres.user").(string)

// or using an intermediate object
postgresConfig := config.Get("postgres").(*toml.Tree)
password := postgresConfig.Get("password").(string)

Or use Unmarshal:

type Postgres struct {
    User     string
    Password string
}
type Config struct {
    Postgres Postgres
}

doc := []byte(`
[Postgres]
User = "pelletier"
Password = "mypassword"`)

config := Config{}
toml.Unmarshal(doc, &config)
fmt.Println("user=", config.Postgres.User)

Or use a query:

// use a query to gather elements without walking the tree
q, _ := query.Compile("$..[user,password]")
results := q.Execute(config)
for ii, item := range results.Values() {
    fmt.Printf("Query result %d: %v\n", ii, item)
}

Documentation

The documentation and additional examples are available at pkg.go.dev.

Tools

Go-toml provides three handy command line tools:

  • tomll: Reads TOML files and lints them.

    go install github.com/pelletier/go-toml/cmd/tomll
    tomll --help
    
  • tomljson: Reads a TOML file and outputs its JSON representation.

    go install github.com/pelletier/go-toml/cmd/tomljson
    tomljson --help
    
  • jsontoml: Reads a JSON file and outputs a TOML representation.

    go install github.com/pelletier/go-toml/cmd/jsontoml
    jsontoml --help
    
Docker image

Those tools are also available as a Docker image from dockerhub. For example, to use tomljson:

docker run -v $PWD:/workdir pelletier/go-toml tomljson /workdir/example.toml

Only master (latest) and tagged versions are published to dockerhub. You can build your own image as usual:

docker build -t go-toml .

Contribute

Feel free to report bugs and patches using GitHub's pull requests system on pelletier/go-toml. Any feedback would be much appreciated!

Run tests

go test ./...

Fuzzing

The script ./fuzz.sh is available to run go-fuzz on go-toml.

Versioning

Go-toml follows Semantic Versioning. The supported version of TOML is indicated at the beginning of this document. The last two major versions of Go are supported (see Go Release Policy).

License

The MIT License (MIT) + Apache 2.0. Read LICENSE.

Documentation

Overview

Package toml is a TOML parser and manipulation library.

This version supports the specification as described in https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.5.0.md

Marshaling

Go-toml can marshal and unmarshal TOML documents from and to data structures.

TOML document as a tree

Go-toml can operate on a TOML document as a tree. Use one of the Load* functions to parse TOML data and obtain a Tree instance, then one of its methods to manipulate the tree.

JSONPath-like queries

The package github.com/pelletier/go-toml/query implements a system similar to JSONPath to quickly retrieve elements of a TOML document using a single expression. See the package documentation for more information.

Package civil implements types for civil time, a time-zone-independent representation of time that follows the rules of the proleptic Gregorian calendar with exactly 24-hour days, 60-minute hours, and 60-second minutes.

Because they lack location information, these types do not represent unique moments or intervals of time. Use time.Time for that purpose.

Example (Tree)
package main

import (
	"fmt"

	toml "github.com/pelletier/go-toml"
)

func main() {
	config, err := toml.LoadFile("config.toml")

	if err != nil {
		fmt.Println("Error ", err.Error())
	} else {
		// retrieve data directly
		directUser := config.Get("postgres.user").(string)
		directPassword := config.Get("postgres.password").(string)
		fmt.Println("User is", directUser, " and password is", directPassword)

		// or using an intermediate object
		configTree := config.Get("postgres").(*toml.Tree)
		user := configTree.Get("user").(string)
		password := configTree.Get("password").(string)
		fmt.Println("User is", user, " and password is", password)

		// show where elements are in the file
		fmt.Printf("User position: %v\n", configTree.GetPosition("user"))
		fmt.Printf("Password position: %v\n", configTree.GetPosition("password"))
	}
}
Output:

Example (Unmarshal)
package main

import (
	"fmt"

	toml "github.com/pelletier/go-toml"
)

func main() {
	type Employer struct {
		Name  string
		Phone string
	}
	type Person struct {
		Name     string
		Age      int64
		Employer Employer
	}

	document := []byte(`
	name = "John"
	age = 30
	[employer]
		name = "Company Inc."
		phone = "+1 234 567 89012"
	`)

	person := Person{}
	toml.Unmarshal(document, &person)
	fmt.Println(person.Name, "is", person.Age, "and works at", person.Employer.Name)
}
Output:

John is 30 and works at Company Inc.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal added in v1.0.0

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

Marshal returns the TOML encoding of v. Behavior is similar to the Go json encoder, except that there is no concept of a Marshaler interface or MarshalTOML function for sub-structs, and currently only definite types can be marshaled (i.e. no `interface{}`).

The following struct annotations are supported:

toml:"Field"      Overrides the field's name to output.
omitempty         When set, empty values and groups are not emitted.
comment:"comment" Emits a # comment on the same line. This supports new lines.
commented:"true"  Emits the value as commented.

Note that pointers are automatically assigned the "omitempty" option, as TOML explicitly does not handle null values (saying instead the label should be dropped).

Tree structural types and corresponding marshal types:

*Tree                            (*)struct, (*)map[string]interface{}
[]*Tree                          (*)[](*)struct, (*)[](*)map[string]interface{}
[]interface{} (as interface{})   (*)[]primitive, (*)[]([]interface{})
interface{}                      (*)primitive

Tree primitive types and corresponding marshal types:

uint64     uint, uint8-uint64, pointers to same
int64      int, int8-uint64, pointers to same
float64    float32, float64, pointers to same
string     string, pointers to same
bool       bool, pointers to same
time.LocalTime  time.LocalTime{}, pointers to same

For additional flexibility, use the Encoder API.

Example
package main

import (
	"fmt"
	"log"

	toml "github.com/pelletier/go-toml"
)

func main() {
	type Postgres struct {
		User     string `toml:"user"`
		Password string `toml:"password"`
		Database string `toml:"db" commented:"true" comment:"not used anymore"`
	}
	type Config struct {
		Postgres Postgres `toml:"postgres" comment:"Postgres configuration"`
	}

	config := Config{Postgres{User: "pelletier", Password: "mypassword", Database: "old_database"}}
	b, err := toml.Marshal(config)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))
}
Output:

# Postgres configuration
[postgres]

  # not used anymore
  # db = "old_database"
  password = "mypassword"
  user = "pelletier"

func Unmarshal added in v1.0.0

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

Unmarshal parses the TOML-encoded data and stores the result in the value pointed to by v. Behavior is similar to the Go json encoder, except that there is no concept of an Unmarshaler interface or UnmarshalTOML function for sub-structs, and currently only definite types can be unmarshaled to (i.e. no `interface{}`).

The following struct annotations are supported:

toml:"Field" Overrides the field's name to map to.
default:"foo" Provides a default value.

For default values, only fields of the following types are supported:

  • string
  • bool
  • int
  • int64
  • float64

See Marshal() documentation for types mapping table.

Example
package main

import (
	"fmt"

	toml "github.com/pelletier/go-toml"
)

func main() {
	type Postgres struct {
		User     string
		Password string
	}
	type Config struct {
		Postgres Postgres
	}

	doc := []byte(`
	[postgres]
	user = "pelletier"
	password = "mypassword"`)

	config := Config{}
	toml.Unmarshal(doc, &config)
	fmt.Println("user=", config.Postgres.User)
}
Output:

user= pelletier

func ValueStringRepresentation added in v1.9.0

func ValueStringRepresentation(v interface{}, commented string, indent string, ord MarshalOrder, arraysOneElementPerLine bool) (string, error)

ValueStringRepresentation transforms an interface{} value into its toml string representation.

Types

type Decoder added in v1.1.0

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

Decoder reads and decodes TOML values from an input stream.

func NewDecoder added in v1.1.0

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r.

func (*Decoder) Decode added in v1.1.0

func (d *Decoder) Decode(v interface{}) error

Decode reads a TOML-encoded value from it's input and unmarshals it in the value pointed at by v.

See the documentation for Marshal for details.

func (*Decoder) SetTagName added in v1.3.0

func (d *Decoder) SetTagName(v string) *Decoder

SetTagName allows changing default tag "toml"

func (*Decoder) Strict added in v1.8.0

func (d *Decoder) Strict(strict bool) *Decoder

Strict allows changing to strict decoding. Any fields that are found in the input data and do not have a corresponding struct member cause an error.

type Encoder added in v1.1.0

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

Encoder writes TOML values to an output stream.

Example (Anonymous)
package main

import (
	"fmt"
	"log"
	"os"

	toml "github.com/pelletier/go-toml"
)

func main() {
	type Credentials struct {
		User     string `toml:"user"`
		Password string `toml:"password"`
	}

	type Protocol struct {
		Name string `toml:"name"`
	}

	type Config struct {
		Version int `toml:"version"`
		Credentials
		Protocol `toml:"Protocol"`
	}
	config := Config{
		Version: 2,
		Credentials: Credentials{
			User:     "pelletier",
			Password: "mypassword",
		},
		Protocol: Protocol{
			Name: "tcp",
		},
	}
	fmt.Println("Default:")
	fmt.Println("---------------")

	def := toml.NewEncoder(os.Stdout)
	if err := def.Encode(config); err != nil {
		log.Fatal(err)
	}

	fmt.Println("---------------")
	fmt.Println("With promotion:")
	fmt.Println("---------------")

	prom := toml.NewEncoder(os.Stdout).PromoteAnonymous(true)
	if err := prom.Encode(config); err != nil {
		log.Fatal(err)
	}
}
Output:

Default:
---------------
password = "mypassword"
user = "pelletier"
version = 2

[Protocol]
  name = "tcp"
---------------
With promotion:
---------------
version = 2

[Credentials]
  password = "mypassword"
  user = "pelletier"

[Protocol]
  name = "tcp"

func NewEncoder added in v1.1.0

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) ArraysWithOneElementPerLine added in v1.1.0

func (e *Encoder) ArraysWithOneElementPerLine(v bool) *Encoder

ArraysWithOneElementPerLine sets up the encoder to encode arrays with more than one element on multiple lines instead of one.

For example:

A = [1,2,3]

Becomes

A = [
  1,
  2,
  3,
]

func (*Encoder) CompactComments added in v1.9.2

func (e *Encoder) CompactComments(cc bool) *Encoder

CompactComments removes the new line before each comment in the tree.

func (*Encoder) Encode added in v1.1.0

func (e *Encoder) Encode(v interface{}) error

Encode writes the TOML encoding of v to the stream.

See the documentation for Marshal for details.

func (*Encoder) Indentation added in v1.8.0

func (e *Encoder) Indentation(indent string) *Encoder

Indentation allows to change indentation when marshalling.

func (*Encoder) Order added in v1.3.0

func (e *Encoder) Order(ord MarshalOrder) *Encoder

Order allows to change in which order fields will be written to the output stream.

func (*Encoder) PromoteAnonymous added in v1.8.0

func (e *Encoder) PromoteAnonymous(promote bool) *Encoder

PromoteAnonymous allows to change how anonymous struct fields are marshaled. Usually, they are marshaled as if the inner exported fields were fields in the outer struct. However, if an anonymous struct field is given a name in its TOML tag, it is treated like a regular struct field with that name. rather than being anonymous.

In case anonymous promotion is enabled, all anonymous structs are promoted and treated like regular struct fields.

func (*Encoder) QuoteMapKeys added in v1.1.0

func (e *Encoder) QuoteMapKeys(v bool) *Encoder

QuoteMapKeys sets up the encoder to encode maps with string type keys with quoted TOML keys.

This relieves the character limitations on map keys.

func (*Encoder) SetTagComment added in v1.3.0

func (e *Encoder) SetTagComment(v string) *Encoder

SetTagComment allows changing default tag "comment"

func (*Encoder) SetTagCommented added in v1.3.0

func (e *Encoder) SetTagCommented(v string) *Encoder

SetTagCommented allows changing default tag "commented"

func (*Encoder) SetTagMultiline added in v1.3.0

func (e *Encoder) SetTagMultiline(v string) *Encoder

SetTagMultiline allows changing default tag "multiline"

func (*Encoder) SetTagName added in v1.3.0

func (e *Encoder) SetTagName(v string) *Encoder

SetTagName allows changing default tag "toml"

type LocalDate added in v1.6.0

type LocalDate struct {
	Year  int        // Year (e.g., 2014).
	Month time.Month // Month of the year (January = 1, ...).
	Day   int        // Day of the month, starting at 1.
}

A LocalDate represents a date (year, month, day).

This type does not include location information, and therefore does not describe a unique 24-hour timespan.

func LocalDateOf added in v1.6.0

func LocalDateOf(t time.Time) LocalDate

LocalDateOf returns the LocalDate in which a time occurs in that time's location.

func ParseLocalDate added in v1.6.0

func ParseLocalDate(s string) (LocalDate, error)

ParseLocalDate parses a string in RFC3339 full-date format and returns the date value it represents.

func (LocalDate) AddDays added in v1.6.0

func (d LocalDate) AddDays(n int) LocalDate

AddDays returns the date that is n days in the future. n can also be negative to go into the past.

func (LocalDate) After added in v1.6.0

func (d1 LocalDate) After(d2 LocalDate) bool

After reports whether d1 occurs after d2.

func (LocalDate) Before added in v1.6.0

func (d1 LocalDate) Before(d2 LocalDate) bool

Before reports whether d1 occurs before d2.

func (LocalDate) DaysSince added in v1.6.0

func (d LocalDate) DaysSince(s LocalDate) (days int)

DaysSince returns the signed number of days between the date and s, not including the end day. This is the inverse operation to AddDays.

func (LocalDate) In added in v1.6.0

func (d LocalDate) In(loc *time.Location) time.Time

In returns the time corresponding to time 00:00:00 of the date in the location.

In is always consistent with time.LocalDate, even when time.LocalDate returns a time on a different day. For example, if loc is America/Indiana/Vincennes, then both

time.LocalDate(1955, time.May, 1, 0, 0, 0, 0, loc)

and

civil.LocalDate{Year: 1955, Month: time.May, Day: 1}.In(loc)

return 23:00:00 on April 30, 1955.

In panics if loc is nil.

func (LocalDate) IsValid added in v1.6.0

func (d LocalDate) IsValid() bool

IsValid reports whether the date is valid.

func (LocalDate) MarshalText added in v1.6.0

func (d LocalDate) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of d.String().

func (LocalDate) String added in v1.6.0

func (d LocalDate) String() string

String returns the date in RFC3339 full-date format.

func (*LocalDate) UnmarshalText added in v1.6.0

func (d *LocalDate) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The date is expected to be a string in a format accepted by ParseLocalDate.

type LocalDateTime added in v1.6.0

type LocalDateTime struct {
	Date LocalDate
	Time LocalTime
}

A LocalDateTime represents a date and time.

This type does not include location information, and therefore does not describe a unique moment in time.

func LocalDateTimeOf added in v1.6.0

func LocalDateTimeOf(t time.Time) LocalDateTime

LocalDateTimeOf returns the LocalDateTime in which a time occurs in that time's location.

func ParseLocalDateTime added in v1.6.0

func ParseLocalDateTime(s string) (LocalDateTime, error)

ParseLocalDateTime parses a string and returns the LocalDateTime it represents. ParseLocalDateTime accepts a variant of the RFC3339 date-time format that omits the time offset but includes an optional fractional time, as described in ParseLocalTime. Informally, the accepted format is

YYYY-MM-DDTHH:MM:SS[.FFFFFFFFF]

where the 'T' may be a lower-case 't'.

func (LocalDateTime) After added in v1.6.0

func (dt1 LocalDateTime) After(dt2 LocalDateTime) bool

After reports whether dt1 occurs after dt2.

func (LocalDateTime) Before added in v1.6.0

func (dt1 LocalDateTime) Before(dt2 LocalDateTime) bool

Before reports whether dt1 occurs before dt2.

func (LocalDateTime) In added in v1.6.0

func (dt LocalDateTime) In(loc *time.Location) time.Time

In returns the time corresponding to the LocalDateTime in the given location.

If the time is missing or ambigous at the location, In returns the same result as time.LocalDate. For example, if loc is America/Indiana/Vincennes, then both

time.LocalDate(1955, time.May, 1, 0, 30, 0, 0, loc)

and

civil.LocalDateTime{
    civil.LocalDate{Year: 1955, Month: time.May, Day: 1}},
    civil.LocalTime{Minute: 30}}.In(loc)

return 23:30:00 on April 30, 1955.

In panics if loc is nil.

func (LocalDateTime) IsValid added in v1.6.0

func (dt LocalDateTime) IsValid() bool

IsValid reports whether the datetime is valid.

func (LocalDateTime) MarshalText added in v1.6.0

func (dt LocalDateTime) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of dt.String().

func (LocalDateTime) String added in v1.6.0

func (dt LocalDateTime) String() string

String returns the date in the format described in ParseLocalDate.

func (*LocalDateTime) UnmarshalText added in v1.6.0

func (dt *LocalDateTime) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The datetime is expected to be a string in a format accepted by ParseLocalDateTime

type LocalTime added in v1.6.0

type LocalTime struct {
	Hour       int // The hour of the day in 24-hour format; range [0-23]
	Minute     int // The minute of the hour; range [0-59]
	Second     int // The second of the minute; range [0-59]
	Nanosecond int // The nanosecond of the second; range [0-999999999]
}

A LocalTime represents a time with nanosecond precision.

This type does not include location information, and therefore does not describe a unique moment in time.

This type exists to represent the TIME type in storage-based APIs like BigQuery. Most operations on Times are unlikely to be meaningful. Prefer the LocalDateTime type.

func LocalTimeOf added in v1.6.0

func LocalTimeOf(t time.Time) LocalTime

LocalTimeOf returns the LocalTime representing the time of day in which a time occurs in that time's location. It ignores the date.

func ParseLocalTime added in v1.6.0

func ParseLocalTime(s string) (LocalTime, error)

ParseLocalTime parses a string and returns the time value it represents. ParseLocalTime accepts an extended form of the RFC3339 partial-time format. After the HH:MM:SS part of the string, an optional fractional part may appear, consisting of a decimal point followed by one to nine decimal digits. (RFC3339 admits only one digit after the decimal point).

func (LocalTime) IsValid added in v1.6.0

func (t LocalTime) IsValid() bool

IsValid reports whether the time is valid.

func (LocalTime) MarshalText added in v1.6.0

func (t LocalTime) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of t.String().

func (LocalTime) String added in v1.6.0

func (t LocalTime) String() string

String returns the date in the format described in ParseLocalTime. If Nanoseconds is zero, no fractional part will be generated. Otherwise, the result will end with a fractional part consisting of a decimal point and nine digits.

func (*LocalTime) UnmarshalText added in v1.6.0

func (t *LocalTime) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be a string in a format accepted by ParseLocalTime.

type MarshalOrder added in v1.9.0

type MarshalOrder int
const (
	// Sort fields alphabetically.
	OrderAlphabetical MarshalOrder = iota + 1
	// Preserve the order the fields are encountered. For example, the order of fields in
	// a struct.
	OrderPreserve
)

Orders the Encoder can write the fields to the output stream.

type Marshaler added in v1.0.0

type Marshaler interface {
	MarshalTOML() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid TOML.

type Position

type Position struct {
	Line int // line within the document
	Col  int // column within the line
}

Position of a document element within a TOML document.

Line and Col are both 1-indexed positions for the element's line number and column number, respectively. Values of zero or less will cause Invalid(), to return true.

func (Position) Invalid

func (p Position) Invalid() bool

Invalid returns whether or not the position is valid (i.e. with negative or null values)

func (Position) String

func (p Position) String() string

String representation of the position. Displays 1-indexed line and column numbers.

type PubTOMLValue added in v1.9.0

type PubTOMLValue = tomlValue

PubTOMLValue wrapping tomlValue in order to access all properties from outside.

func (*PubTOMLValue) Comment added in v1.9.0

func (ptv *PubTOMLValue) Comment() string

func (*PubTOMLValue) Commented added in v1.9.0

func (ptv *PubTOMLValue) Commented() bool

func (*PubTOMLValue) Multiline added in v1.9.0

func (ptv *PubTOMLValue) Multiline() bool

func (*PubTOMLValue) Position added in v1.9.0

func (ptv *PubTOMLValue) Position() Position

func (*PubTOMLValue) SetComment added in v1.9.0

func (ptv *PubTOMLValue) SetComment(s string)

func (*PubTOMLValue) SetCommented added in v1.9.0

func (ptv *PubTOMLValue) SetCommented(c bool)

func (*PubTOMLValue) SetMultiline added in v1.9.0

func (ptv *PubTOMLValue) SetMultiline(m bool)

func (*PubTOMLValue) SetPosition added in v1.9.0

func (ptv *PubTOMLValue) SetPosition(p Position)

func (*PubTOMLValue) SetValue added in v1.9.0

func (ptv *PubTOMLValue) SetValue(v interface{})

func (*PubTOMLValue) Value added in v1.9.0

func (ptv *PubTOMLValue) Value() interface{}

type PubTree added in v1.9.0

type PubTree = Tree

PubTree wrapping Tree in order to access all properties from outside.

func (*PubTree) Comment added in v1.9.0

func (pt *PubTree) Comment() string

func (*PubTree) Commented added in v1.9.0

func (pt *PubTree) Commented() bool

func (*PubTree) Inline added in v1.9.0

func (pt *PubTree) Inline() bool

func (*PubTree) SetComment added in v1.9.0

func (pt *PubTree) SetComment(c string)

func (*PubTree) SetCommented added in v1.9.0

func (pt *PubTree) SetCommented(c bool)

func (*PubTree) SetInline added in v1.9.0

func (pt *PubTree) SetInline(i bool)

func (*PubTree) SetValues added in v1.9.0

func (pt *PubTree) SetValues(v map[string]interface{})

func (*PubTree) Values added in v1.9.0

func (pt *PubTree) Values() map[string]interface{}

type SetOptions added in v1.2.0

type SetOptions struct {
	Comment   string
	Commented bool
	Multiline bool
	Literal   bool
}

SetOptions arguments are supplied to the SetWithOptions and SetPathWithOptions functions to modify marshalling behaviour. The default values within the struct are valid default options.

type Tree added in v1.0.0

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

Tree is the result of the parsing of a TOML file.

func Load

func Load(content string) (tree *Tree, err error)

Load creates a Tree from a string.

func LoadBytes added in v1.0.1

func LoadBytes(b []byte) (tree *Tree, err error)

LoadBytes creates a Tree from a []byte.

func LoadFile

func LoadFile(path string) (tree *Tree, err error)

LoadFile creates a Tree from a file.

func LoadReader

func LoadReader(reader io.Reader) (tree *Tree, err error)

LoadReader creates a Tree from any io.Reader.

func TreeFromMap

func TreeFromMap(m map[string]interface{}) (*Tree, error)

TreeFromMap initializes a new Tree object using the given map.

func (*Tree) Delete added in v1.3.0

func (t *Tree) Delete(key string) error

Delete removes a key from the tree. Key is a dot-separated path (e.g. a.b.c).

func (*Tree) DeletePath added in v1.3.0

func (t *Tree) DeletePath(keys []string) error

DeletePath removes a key from the tree. Keys is an array of path elements (e.g. {"a","b","c"}).

func (*Tree) Get added in v1.0.0

func (t *Tree) Get(key string) interface{}

Get the value at key in the Tree. Key is a dot-separated path (e.g. a.b.c) without single/double quoted strings. If you need to retrieve non-bare keys, use GetPath. Returns nil if the path does not exist in the tree. If keys is of length zero, the current tree is returned.

func (*Tree) GetArray added in v1.8.1

func (t *Tree) GetArray(key string) interface{}

GetArray returns the value at key in the Tree. It returns []string, []int64, etc type if key has homogeneous lists Key is a dot-separated path (e.g. a.b.c) without single/double quoted strings. Returns nil if the path does not exist in the tree. If keys is of length zero, the current tree is returned.

func (*Tree) GetArrayPath added in v1.8.1

func (t *Tree) GetArrayPath(keys []string) interface{}

GetArrayPath returns the element in the tree indicated by 'keys'. If keys is of length zero, the current tree is returned.

func (*Tree) GetDefault added in v1.0.0

func (t *Tree) GetDefault(key string, def interface{}) interface{}

GetDefault works like Get but with a default value

func (*Tree) GetPath added in v1.0.0

func (t *Tree) GetPath(keys []string) interface{}

GetPath returns the element in the tree indicated by 'keys'. If keys is of length zero, the current tree is returned.

func (*Tree) GetPosition added in v1.0.0

func (t *Tree) GetPosition(key string) Position

GetPosition returns the position of the given key.

func (*Tree) GetPositionPath added in v1.0.0

func (t *Tree) GetPositionPath(keys []string) Position

GetPositionPath returns the element in the tree indicated by 'keys'. If keys is of length zero, the current tree is returned.

func (*Tree) Has added in v1.0.0

func (t *Tree) Has(key string) bool

Has returns a boolean indicating if the given key exists.

func (*Tree) HasPath added in v1.0.0

func (t *Tree) HasPath(keys []string) bool

HasPath returns true if the given path of keys exists, false otherwise.

func (*Tree) Keys added in v1.0.0

func (t *Tree) Keys() []string

Keys returns the keys of the toplevel tree (does not recurse).

func (*Tree) Marshal added in v1.1.0

func (t *Tree) Marshal() ([]byte, error)

Marshal returns the TOML encoding of Tree. See Marshal() documentation for types mapping table.

func (*Tree) Position added in v1.0.0

func (t *Tree) Position() Position

Position returns the position of the tree.

func (*Tree) Set added in v1.0.0

func (t *Tree) Set(key string, value interface{})

Set an element in the tree. Key is a dot-separated path (e.g. a.b.c). Creates all necessary intermediate trees, if needed.

func (*Tree) SetPath added in v1.0.0

func (t *Tree) SetPath(keys []string, value interface{})

SetPath sets an element in the tree. Keys is an array of path elements (e.g. {"a","b","c"}). Creates all necessary intermediate trees, if needed.

func (*Tree) SetPathWithComment added in v1.1.0

func (t *Tree) SetPathWithComment(keys []string, comment string, commented bool, value interface{})

SetPathWithComment is the same as SetPath, but allows you to provide comment information to the key, that will be reused by Marshal().

func (*Tree) SetPathWithOptions added in v1.2.0

func (t *Tree) SetPathWithOptions(keys []string, opts SetOptions, value interface{})

SetPathWithOptions is the same as SetPath, but allows you to provide formatting instructions to the key, that will be reused by Marshal().

func (*Tree) SetPositionPath added in v1.8.1

func (t *Tree) SetPositionPath(keys []string, pos Position)

SetPositionPath sets the position of element in the tree indicated by 'keys'. If keys is of length zero, the current tree position is set.

func (*Tree) SetWithComment added in v1.1.0

func (t *Tree) SetWithComment(key string, comment string, commented bool, value interface{})

SetWithComment is the same as Set, but allows you to provide comment information to the key, that will be reused by Marshal().

func (*Tree) SetWithOptions added in v1.2.0

func (t *Tree) SetWithOptions(key string, opts SetOptions, value interface{})

SetWithOptions is the same as Set, but allows you to provide formatting instructions to the key, that will be used by Marshal().

func (*Tree) String added in v1.0.0

func (t *Tree) String() string

String generates a human-readable representation of the current tree. Alias of ToString. Present to implement the fmt.Stringer interface.

func (*Tree) ToMap added in v1.0.0

func (t *Tree) ToMap() map[string]interface{}

ToMap recursively generates a representation of the tree using Go built-in structures. The following types are used:

  • bool
  • float64
  • int64
  • string
  • uint64
  • time.Time
  • map[string]interface{} (where interface{} is any of this list)
  • []interface{} (where interface{} is any of this list)

func (*Tree) ToTomlString added in v1.0.0

func (t *Tree) ToTomlString() (string, error)

ToTomlString generates a human-readable representation of the current tree. Output spans multiple lines, and is suitable for ingest by a TOML parser. If the conversion cannot be performed, ToString returns a non-nil error.

func (*Tree) Unmarshal added in v1.0.0

func (t *Tree) Unmarshal(v interface{}) error

Unmarshal attempts to unmarshal the Tree into a Go struct pointed by v. Neither Unmarshaler interfaces nor UnmarshalTOML functions are supported for sub-structs, and only definite types can be unmarshaled.

func (*Tree) WriteTo added in v1.0.0

func (t *Tree) WriteTo(w io.Writer) (int64, error)

WriteTo encode the Tree as Toml and writes it to the writer w. Returns the number of bytes written in case of success, or an error if anything happened.

type Unmarshaler added in v1.8.0

type Unmarshaler interface {
	UnmarshalTOML(interface{}) error
}

Unmarshaler is the interface implemented by types that can unmarshal a TOML description of themselves.

Directories

Path Synopsis
cmd
jsontoml
Jsontoml reads JSON and converts to TOML.
Jsontoml reads JSON and converts to TOML.
tomljson
Tomljson reads TOML and converts to JSON.
Tomljson reads TOML and converts to JSON.
tomll
Tomll is a linter for TOML
Tomll is a linter for TOML
tomltestgen
Tomltestgen is a program that retrieves a given version of https://github.com/BurntSushi/toml-test and generates go code for go-toml's unit tests based on the test files.
Tomltestgen is a program that retrieves a given version of https://github.com/BurntSushi/toml-test and generates go code for go-toml's unit tests based on the test files.
Package query performs JSONPath-like queries on a TOML document.
Package query performs JSONPath-like queries on a TOML document.

Jump to

Keyboard shortcuts

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