README ¶
TOML parser and encoder for Go with reflection
TOML stands for Tom's Obvious, Minimal Language. This Go package provides a
reflection interface similar to Go's standard library json
and xml
packages. This package also supports the encoding.TextUnmarshaler
and
encoding.TextMarshaler
interfaces so that you can define custom data
representations. (There is an example of this below.)
Spec: https://github.com/toml-lang/toml
Compatible with TOML version v0.4.0
Documentation: https://godoc.org/github.com/BurntSushi/toml
Installation:
go get github.com/BurntSushi/toml
Try the toml validator:
go get github.com/BurntSushi/toml/cmd/tomlv
tomlv some-toml-file.toml
Testing
This package passes all tests in toml-test for both the decoder and the encoder.
Examples
This package works similarly to how the Go standard library handles XML
and JSON
. Namely, data is loaded into Go values via reflection.
For the simplest example, consider some TOML file as just a list of keys and values:
Age = 25
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z
Which could be defined in Go as:
type Config struct {
Age int
Cats []string
Pi float64
Perfection []int
DOB time.Time // requires `import time`
}
And then decoded with:
var conf Config
if _, err := toml.Decode(tomlData, &conf); err != nil {
// handle error
}
You can also use struct tags if your struct field name doesn't map to a TOML key value directly:
some_key_NAME = "wat"
type TOML struct {
ObscureKey string `toml:"some_key_NAME"`
}
Using the encoding.TextUnmarshaler
interface
Here's an example that automatically parses duration strings into
time.Duration
values:
[[song]]
name = "Thunder Road"
duration = "4m49s"
[[song]]
name = "Stairway to Heaven"
duration = "8m03s"
Which can be decoded with:
type song struct {
Name string
Duration duration
}
type songs struct {
Song []song
}
var favorites songs
if _, err := toml.Decode(blob, &favorites); err != nil {
log.Fatal(err)
}
for _, s := range favorites.Song {
fmt.Printf("%s (%s)\n", s.Name, s.Duration)
}
And you'll also need a duration
type that satisfies the
encoding.TextUnmarshaler
interface:
type duration struct {
time.Duration
}
func (d *duration) UnmarshalText(text []byte) error {
var err error
d.Duration, err = time.ParseDuration(string(text))
return err
}
More complex usage
Here's an example of how to load the example from the official spec page:
# This is a TOML document. Boom.
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
organization = "GitHub"
bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
dob = 1979-05-27T07:32:00Z # First class dates? Why not?
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true
[servers]
# You can indent as you please. Tabs or spaces. TOML don't care.
[servers.alpha]
ip = "10.0.0.1"
dc = "eqdc10"
[servers.beta]
ip = "10.0.0.2"
dc = "eqdc10"
[clients]
data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
# Line breaks are OK when inside arrays
hosts = [
"alpha",
"omega"
]
And the corresponding Go types are:
type tomlConfig struct {
Title string
Owner ownerInfo
DB database `toml:"database"`
Servers map[string]server
Clients clients
}
type ownerInfo struct {
Name string
Org string `toml:"organization"`
Bio string
DOB time.Time
}
type database struct {
Server string
Ports []int
ConnMax int `toml:"connection_max"`
Enabled bool
}
type server struct {
IP string
DC string
}
type clients struct {
Data [][]interface{}
Hosts []string
}
Note that a case insensitive match will be tried if an exact match can't be found.
A working example of the above can be found in _examples/example.{go,toml}
.
Documentation ¶
Overview ¶
Package toml provides facilities for decoding and encoding TOML configuration files via reflection. There is also support for delaying decoding with the Primitive type, and querying the set of keys in a TOML document with the MetaData type.
The specification implemented: https://github.com/toml-lang/toml
The sub-command github.com/BurntSushi/toml/cmd/tomlv can be used to verify whether a file is a valid TOML document. It can also be used to print the type of each key in a TOML document.
Testing ¶
There are two important types of tests used for this package. The first is contained inside '*_test.go' files and uses the standard Go unit testing framework. These tests are primarily devoted to holistically testing the decoder and encoder.
The second type of testing is used to verify the implementation's adherence to the TOML specification. These tests have been factored into their own project: https://github.com/BurntSushi/toml-test
The reason the tests are in a separate project is so that they can be used by any implementation of TOML. Namely, it is language agnostic.
Example (StrictDecoding) ¶
Example StrictDecoding shows how to detect whether there are keys in the TOML document that weren't decoded into the value given. This is useful for returning an error to the user if they've included extraneous fields in their configuration.
Output: Undecoded keys: ["key2"]
Example (UnmarshalTOML) ¶
Example UnmarshalTOML shows how to implement a struct type that knows how to unmarshal itself. The struct must take full responsibility for mapping the values passed into the struct. The method may be used with interfaces in a struct in cases where the actual type is not known until the data is examined.
Output: 4 VALVE: valve-1 VALVE: valve-2 PIPE: pipe-1 CABLE: cable-1
Example (Unmarshaler) ¶
Example Unmarshaler shows how to decode TOML strings into your own custom data type.
Output: Thunder Road (4m49s) Stairway to Heaven (8m3s)
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Encoder ¶
type Encoder struct { // A single indentation level. By default it is two spaces. Indent string // contains filtered or unexported fields }
Encoder controls the encoding of Go values to a TOML document to some io.Writer.
The indentation level can be controlled with the Indent field.
func NewEncoder ¶
NewEncoder returns a TOML encoder that encodes Go values to the io.Writer given. By default, a single indentation level is 2 spaces.
func (*Encoder) Encode ¶
Encode writes a TOML representation of the Go value to the underlying io.Writer. If the value given cannot be encoded to a valid TOML document, then an error is returned.
The mapping between Go values and TOML values should be precisely the same as for the Decode* functions. Similarly, the TextMarshaler interface is supported by encoding the resulting bytes as strings. (If you want to write arbitrary binary data then you will need to use something like base64 since TOML does not have any binary types.)
When encoding TOML hashes (i.e., Go maps or structs), keys without any sub-hashes are encoded first.
If a Go map is encoded, then its keys are sorted alphabetically for deterministic output. More control over this behavior may be provided if there is demand for it.
Encoding Go values without a corresponding TOML representation---like map types with non-string keys---will cause an error to be returned. Similarly for mixed arrays/slices, arrays/slices with nil elements, embedded non-struct types and nested slices containing maps or structs. (e.g., [][]map[string]string is not allowed but []map[string]string is OK and so is []map[string][]string.)
Example ¶
Output: counts = [1, 1, 2, 3, 5, 8] date = 2010-03-14T18:00:00Z [hash] key1 = "val1" key2 = "val2"
type Key ¶
type Key []string
Key is the type of any TOML key, including key groups. Use (MetaData).Keys to get values of this type.
type MetaData ¶
type MetaData struct {
// contains filtered or unexported fields
}
MetaData allows access to meta information about TOML data that may not be inferrable via reflection. In particular, whether a key has been defined and the TOML type of a key.
func Decode ¶
Decode will decode the contents of `data` in TOML format into a pointer `v`.
TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be used interchangeably.)
TOML arrays of tables correspond to either a slice of structs or a slice of maps.
TOML datetimes correspond to Go `time.Time` values.
All other TOML types (float, string, int, bool and array) correspond to the obvious Go types.
An exception to the above rules is if a type implements the encoding.TextUnmarshaler interface. In this case, any primitive TOML value (floats, strings, integers, booleans and datetimes) will be converted to a byte string and given to the value's UnmarshalText method. See the Unmarshaler example for a demonstration with time duration strings.
Key mapping ¶
TOML keys can map to either keys in a Go map or field names in a Go struct. The special `toml` struct tag may be used to map TOML keys to struct fields that don't match the key name exactly. (See the example.) A case insensitive match to struct names will be tried if an exact match can't be found.
The mapping between TOML values and Go values is loose. That is, there may exist TOML values that cannot be placed into your representation, and there may be parts of your representation that do not correspond to TOML values. This loose mapping can be made stricter by using the IsDefined and/or Undecoded methods on the MetaData returned.
This decoder will not handle cyclic types. If a cyclic type is passed, `Decode` will not terminate.
Example ¶
Output: Server: alpha (ip: 10.0.0.1) in Toronto created on 1987-07-05 Ports: [8001 8002] Server: beta (ip: 10.0.0.2) in New Jersey created on 1887-01-05 Ports: [9001 9002]
func DecodeFile ¶
DecodeFile is just like Decode, except it will automatically read the contents of the file at `fpath` and decode it for you.
func DecodeReader ¶
DecodeReader is just like Decode, except it will consume all bytes from the reader and decode it for you.
func (*MetaData) IsDefined ¶
IsDefined returns true if the key given exists in the TOML data. The key should be specified hierarchially. e.g.,
// access the TOML key 'a.b.c' IsDefined("a", "b", "c")
IsDefined will return false if an empty key given. Keys are case sensitive.
func (*MetaData) Keys ¶
Keys returns a slice of every key in the TOML data, including key groups. Each key is itself a slice, where the first element is the top of the hierarchy and the last is the most specific.
The list will have the same order as the keys appeared in the TOML data.
All keys returned are non-empty.
func (*MetaData) PrimitiveDecode ¶
PrimitiveDecode is just like the other `Decode*` functions, except it decodes a TOML value that has already been parsed. Valid primitive values can *only* be obtained from values filled by the decoder functions, including this method. (i.e., `v` may contain more `Primitive` values.)
Meta data for primitive values is included in the meta data returned by the `Decode*` functions with one exception: keys returned by the Undecoded method will only reflect keys that were decoded. Namely, any keys hidden behind a Primitive will be considered undecoded. Executing this method will update the undecoded keys in the meta data. (See the example.)
Example ¶
Output: Is `bands.Springsteen` defined? true Springsteen started in 1973. J Geils started in 1970. Undecoded: []
func (*MetaData) Type ¶
Type returns a string representation of the type of the key specified.
Type will return the empty string if given an empty key or a key that does not exist. Keys are case sensitive.
func (*MetaData) Undecoded ¶
Undecoded returns all keys that have not been decoded in the order in which they appear in the original TOML document.
This includes keys that haven't been decoded because of a Primitive value. Once the Primitive value is decoded, the keys will be considered decoded.
Also note that decoding into an empty interface will result in no decoding, and so no keys will be considered decoded.
In this sense, the Undecoded keys correspond to keys in the TOML document that do not have a concrete type in your representation.
type Primitive ¶
type Primitive struct {
// contains filtered or unexported fields
}
Primitive is a TOML value that hasn't been decoded into a Go value. When using the various `Decode*` functions, the type `Primitive` may be given to any value, and its decoding will be delayed.
A `Primitive` value can be decoded using the `PrimitiveDecode` function.
The underlying representation of a `Primitive` value is subject to change. Do not rely on it.
N.B. Primitive values are still parsed, so using them will only avoid the overhead of reflection. They can be useful when you don't know the exact type of TOML data until run time.
type TextMarshaler ¶
type TextMarshaler encoding.TextMarshaler
TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here so that Go 1.1 can be supported.
type TextUnmarshaler ¶
type TextUnmarshaler encoding.TextUnmarshaler
TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined here so that Go 1.1 can be supported.
type Unmarshaler ¶
type Unmarshaler interface {
UnmarshalTOML(interface{}) error
}
Unmarshaler is the interface implemented by objects that can unmarshal a TOML description of themselves.
Notes ¶
Bugs ¶
The behavior here is incorrect whenever a Go type satisfies the encoding.TextUnmarshaler interface but also corresponds to a TOML hash or array. In particular, the unmarshaler should only be applied to primitive TOML values. But at this point, it will be applied to all kinds of values and produce an incorrect error whenever those values are hashes or arrays (including arrays of tables).
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
toml-test-decoder
Command toml-test-decoder satisfies the toml-test interface for testing TOML decoders.
|
Command toml-test-decoder satisfies the toml-test interface for testing TOML decoders. |
toml-test-encoder
Command toml-test-encoder satisfies the toml-test interface for testing TOML encoders.
|
Command toml-test-encoder satisfies the toml-test interface for testing TOML encoders. |
tomlv
Command tomlv validates TOML documents and prints each key's type.
|
Command tomlv validates TOML documents and prints each key's type. |