toml

package module
v2.4.3 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 17 Imported by: 1,986

README

go-toml v2

Go library for the TOML format.

This library supports TOML v1.1.0.

🐞 Bug Reports

💬 Anything else

Documentation

Full API, examples, and implementation notes are available in the Go documentation.

Go Reference

Import

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

Features

Stdlib behavior

As much as possible, this library is designed to behave similarly as the standard library's encoding/json.

When encoding structs, fields tagged with omitempty are omitted if they are empty. For time.Time, the zero value is considered empty, so timestamps such as created_at or updated_at are not written unless you remove omitempty from the struct tag or use a pointer type (*time.Time).

Performance

While go-toml favors usability, it is written with performance in mind. Most operations should not be shockingly slow. See benchmarks.

Strict mode

Decoder can be set to "strict mode", which makes it error when some parts of the TOML document was not present in the target structure. This is a great way to check for typos. See example in the documentation.

Contextualized errors

When most decoding errors occur, go-toml returns DecodeError, which contains a human readable contextualized version of the error. For example:

1| [server]
2| path = 100
 |        ~~~ cannot decode TOML integer into struct field toml_test.Server.Path of type string
3| port = 50
Local date and time support

TOML supports native local date/times. It allows to represent a given date, time, or date-time without relation to a timezone or offset. To support this use-case, go-toml provides LocalDate, LocalTime, and LocalDateTime. Those types can be transformed to and from time.Time, making them convenient yet unambiguous structures for their respective TOML representation.

Commented config

Since TOML is often used for configuration files, go-toml can emit documents annotated with comments and commented-out values. For example, it can generate the following file:

# Host IP to connect to.
host = '127.0.0.1'
# Port of the remote server.
port = 4242

# Encryption parameters (optional)
# [TLS]
# cipher = 'AEAD-AES128-GCM-SHA256'
# version = 'TLS 1.3'

Getting started

Given the following struct, let's see how to read it and write it as TOML:

type MyConfig struct {
	Version int
	Name    string
	Tags    []string
}
Unmarshaling

Unmarshal reads a TOML document and fills a Go structure with its content.

Note that the struct variable names are capitalized, while the variables in the toml document are lowercase.

For example:

doc := `
version = 2
name = "go-toml"
tags = ["go", "toml"]
`

var cfg MyConfig
err := toml.Unmarshal([]byte(doc), &cfg)
if err != nil {
	panic(err)
}
fmt.Println("version:", cfg.Version)
fmt.Println("name:", cfg.Name)
fmt.Println("tags:", cfg.Tags)

// Output:
// version: 2
// name: go-toml
// tags: [go toml]

Here is an example using tables with some simple nesting:

doc := `
age = 45
fruits = ["apple", "pear"]

# these are very important!
[my-variables]
first = 1
second = 0.2
third = "abc"

# this is not so important.
[my-variables.b]
bfirst = 123
`

var Document struct {
	Age int
	Fruits []string

	Myvariables struct {
		First  int
		Second float64
		Third  string

		B struct {
			Bfirst int
		}
	} `toml:"my-variables"`
}

err := toml.Unmarshal([]byte(doc), &Document)
if err != nil {
	panic(err)
}

fmt.Println("age:", Document.Age)
fmt.Println("fruits:", Document.Fruits)
fmt.Println("my-variables.first:", Document.Myvariables.First)
fmt.Println("my-variables.second:", Document.Myvariables.Second)
fmt.Println("my-variables.third:", Document.Myvariables.Third)
fmt.Println("my-variables.B.Bfirst:", Document.Myvariables.B.Bfirst)

// Output:
// age: 45
// fruits: [apple pear]
// my-variables.first: 1
// my-variables.second: 0.2
// my-variables.third: abc
// my-variables.B.Bfirst: 123
Marshaling

Marshal is the opposite of Unmarshal: it represents a Go structure as a TOML document:

cfg := MyConfig{
	Version: 2,
	Name:    "go-toml",
	Tags:    []string{"go", "toml"},
}

b, err := toml.Marshal(cfg)
if err != nil {
	panic(err)
}
fmt.Println(string(b))

// Output:
// Version = 2
// Name = 'go-toml'
// Tags = ['go', 'toml']

Unstable API

This API does not yet follow the backward compatibility guarantees of this library. They provide early access to features that may have rough edges or an API subject to change.

Parser

Parser is the unstable API that allows iterative parsing of a TOML document at the AST level. See https://pkg.go.dev/github.com/pelletier/go-toml/v2/unstable.

Benchmarks

Execution time speedup compared to other Go TOML libraries:

Benchmarkgo-toml v1BurntSushi/toml
Marshal/HugoFrontMatter-22.3x2.4x
Marshal/ReferenceFile/map-22.2x2.6x
Marshal/ReferenceFile/struct-24.9x5.0x
Unmarshal/HugoFrontMatter-27.8x5.9x
Unmarshal/ReferenceFile/map-26.8x6.4x
Unmarshal/ReferenceFile/struct-26.8x6.3x
See more

The table above has the results of the most common use-cases. The table below contains the results of all benchmarks, including unrealistic ones. It is provided for completeness.

Benchmarkgo-toml v1BurntSushi/toml
Marshal/SimpleDocument/map-22.1x3.1x
Marshal/SimpleDocument/struct-23.4x4.8x
Unmarshal/SimpleDocument/map-210.1x7.0x
Unmarshal/SimpleDocument/struct-212.4x8.0x
UnmarshalDataset/example-28.2x6.9x
UnmarshalDataset/code-27.5x8.3x
UnmarshalDataset/twitter-29.0x7.6x
UnmarshalDataset/citm_catalog-25.0x4.5x
UnmarshalDataset/canada-26.4x4.7x
UnmarshalDataset/config-210.2x6.1x
geomean5.8x5.3x

This table can be generated with ./ci.sh benchmark -a -html.

Tools

Go-toml provides three handy command line tools:

  • tomljson: Reads a TOML file and outputs its JSON representation.

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

    $ go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest
    $ jsontoml --help
    
  • tomll: Lints and reformats a TOML file.

    $ go install github.com/pelletier/go-toml/v2/cmd/tomll@latest
    $ tomll --help
    
Docker image

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

docker run -i ghcr.io/pelletier/go-toml:v2 tomljson < example.toml

Multiple versions are available on ghcr.io.

Versioning

Expect for parts explicitly marked otherwise, 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). Read LICENSE.

Documentation

Overview

Package toml is a library to read and write TOML documents.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal

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

Marshal serializes a Go value as a TOML document.

It is a shortcut for Encoder.Encode() with the default options.

Example
package main

import (
	"fmt"

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

func main() {
	type MyConfig struct {
		Version int
		Name    string
		Tags    []string
	}

	cfg := MyConfig{
		Version: 2,
		Name:    "go-toml",
		Tags:    []string{"go", "toml"},
	}

	b, err := toml.Marshal(cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

}
Output:
Version = 2
Name = 'go-toml'
Tags = ['go', 'toml']
Example (Commented)

Example that uses the 'commented' field tag option to generate an example configuration file that has commented out sections (example from go-graphite/graphite-clickhouse).

package main

import (
	"fmt"
	"time"

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

func main() {
	type Common struct {
		Listen               string        `toml:"listen"                     comment:"general listener"`
		PprofListen          string        `toml:"pprof-listen"               comment:"listener to serve /debug/pprof requests. '-pprof' argument overrides it"`                    //nolint:lll
		MaxMetricsPerTarget  int           `toml:"max-metrics-per-target"     comment:"limit numbers of queried metrics per target in /render requests, 0 or negative = unlimited"` //nolint:lll
		MemoryReturnInterval time.Duration `toml:"memory-return-interval"     comment:"daemon will return the freed memory to the OS when it>0"`
	}

	type Costs struct {
		Cost       *int           `toml:"cost"        comment:"default cost (for wildcarded equivalence or matched with regex, or if no value cost set)"`
		ValuesCost map[string]int `toml:"values-cost" comment:"cost with some value (for equivalence without wildcards) (additional tuning, usually not needed)"` //nolint:lll
	}

	type ClickHouse struct {
		URL string `toml:"url" comment:"default url, see https://clickhouse.tech/docs/en/interfaces/http. Can be overwritten with query-params"`

		RenderMaxQueries        int               `toml:"render-max-queries" comment:"Max queries to render queries"`
		RenderConcurrentQueries int               `toml:"render-concurrent-queries" comment:"Concurrent queries to render queries"`
		TaggedCosts             map[string]*Costs `toml:"tagged-costs,commented"`
		TreeTable               string            `toml:"tree-table,commented"`
		ReverseTreeTable        string            `toml:"reverse-tree-table,commented"`
		DateTreeTable           string            `toml:"date-tree-table,commented"`
		DateTreeTableVersion    int               `toml:"date-tree-table-version,commented"`
		TreeTimeout             time.Duration     `toml:"tree-timeout,commented"`
		TagTable                string            `toml:"tag-table,commented"`
		ExtraPrefix             string            `toml:"extra-prefix"             comment:"add extra prefix (directory in graphite) for all metrics, w/o trailing dot"` //nolint:lll
		ConnectTimeout          time.Duration     `toml:"connect-timeout"          comment:"TCP connection timeout"`
		DataTableLegacy         string            `toml:"data-table,commented"`
		RollupConfLegacy        string            `toml:"rollup-conf,commented"`
		MaxDataPoints           int               `toml:"max-data-points"          comment:"max points per metric when internal-aggregation=true"`
		InternalAggregation     bool              `toml:"internal-aggregation"     comment:"ClickHouse-side aggregation, see doc/aggregation.md"`
	}

	type Tags struct {
		Rules      string `toml:"rules"`
		Date       string `toml:"date"`
		ExtraWhere string `toml:"extra-where"`
		InputFile  string `toml:"input-file"`
		OutputFile string `toml:"output-file"`
	}

	type Config struct {
		Common     Common     `toml:"common"`
		ClickHouse ClickHouse `toml:"clickhouse"`
		Tags       Tags       `toml:"tags,commented"`
	}

	cfg := &Config{
		Common: Common{
			Listen:               ":9090",
			PprofListen:          "",
			MaxMetricsPerTarget:  15000, // This is arbitrary value to protect CH from overload
			MemoryReturnInterval: 0,
		},
		ClickHouse: ClickHouse{
			URL:                 "http://localhost:8123?cancel_http_readonly_queries_on_client_close=1",
			ExtraPrefix:         "",
			ConnectTimeout:      time.Second,
			DataTableLegacy:     "",
			RollupConfLegacy:    "auto",
			MaxDataPoints:       1048576,
			InternalAggregation: true,
		},
		Tags: Tags{},
	}

	out, err := toml.Marshal(cfg)
	if err != nil {
		panic(err)
	}
	err = toml.Unmarshal(out, &cfg)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(out))

}
Output:
[common]
# general listener
listen = ':9090'
# listener to serve /debug/pprof requests. '-pprof' argument overrides it
pprof-listen = ''
# limit numbers of queried metrics per target in /render requests, 0 or negative = unlimited
max-metrics-per-target = 15000
# daemon will return the freed memory to the OS when it>0
memory-return-interval = 0

[clickhouse]
# default url, see https://clickhouse.tech/docs/en/interfaces/http. Can be overwritten with query-params
url = 'http://localhost:8123?cancel_http_readonly_queries_on_client_close=1'
# Max queries to render queries
render-max-queries = 0
# Concurrent queries to render queries
render-concurrent-queries = 0
# tree-table = ''
# reverse-tree-table = ''
# date-tree-table = ''
# date-tree-table-version = 0
# tree-timeout = 0
# tag-table = ''
# add extra prefix (directory in graphite) for all metrics, w/o trailing dot
extra-prefix = ''
# TCP connection timeout
connect-timeout = 1000000000
# data-table = ''
# rollup-conf = 'auto'
# max points per metric when internal-aggregation=true
max-data-points = 1048576
# ClickHouse-side aggregation, see doc/aggregation.md
internal-aggregation = true

# [tags]
# rules = ''
# date = ''
# extra-where = ''
# input-file = ''
# output-file = ''

func Unmarshal

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

Unmarshal deserializes a TOML document into a Go value.

It is a shortcut for Decoder.Decode() with the default options.

Example
package main

import (
	"fmt"

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

func main() {
	type MyConfig struct {
		Version int
		Name    string
		Tags    []string
	}

	doc := `
	version = 2
	name = "go-toml"
	tags = ["go", "toml"]
	`

	var cfg MyConfig
	err := toml.Unmarshal([]byte(doc), &cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println("version:", cfg.Version)
	fmt.Println("name:", cfg.Name)
	fmt.Println("tags:", cfg.Tags)
}
Output:
version: 2
name: go-toml
tags: [go toml]
Example (TextUnmarshal)
package main

import (
	"fmt"
	"log"
	"strconv"

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

type customInt int

func (i *customInt) UnmarshalText(b []byte) error {
	x, err := strconv.ParseInt(string(b), 10, 32)
	if err != nil {
		return err
	}
	*i = customInt(x * 100)
	return nil
}

type doc struct {
	Value customInt
}

func main() {
	var x doc

	data := []byte(`value  = "42"`)
	err := toml.Unmarshal(data, &x)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(x)
}
Output:
{4200}

Types

type DecodeError

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

DecodeError represents an error encountered during the parsing or decoding of a TOML document.

In addition to the error message, it contains the position in the document where it happened, as well as a human-readable representation that shows where the error occurred in the document.

Example
doc := `name = 123__456`

s := map[string]interface{}{}
err := Unmarshal([]byte(doc), &s)

fmt.Println(err)

var derr *DecodeError
if errors.As(err, &derr) {
	fmt.Println(derr.String())
	row, col := derr.Position()
	fmt.Println("error occurred at row", row, "column", col)
}
Output:
toml: number must have at least one digit between underscores
1| name = 123__456
 |           ~~ number must have at least one digit between underscores
error occurred at row 1 column 11

func (*DecodeError) Error

func (e *DecodeError) Error() string

Error returns the error message contained in the DecodeError.

func (*DecodeError) Key

func (e *DecodeError) Key() Key

Key that was being processed when the error occurred.

func (*DecodeError) Position

func (e *DecodeError) Position() (row int, column int)

Position returns the (line, column) pair indicating where the error occurred in the document. Positions are 1-indexed.

func (*DecodeError) String

func (e *DecodeError) String() string

String returns the human-readable contextualized error. This string is multi-line.

type Decoder

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

Decoder reads and decode a TOML document from an input stream.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder creates a new Decoder that will read from r.

func (*Decoder) Decode

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

Decode the whole content of r into v.

By default, values in the document that don't exist in the target Go value are ignored. See Decoder.DisallowUnknownFields() to change this behavior.

When a TOML local date, time, or date-time is decoded into a time.Time, its value is represented in time.Local timezone. Otherwise the appropriate Local* structure is used. For time values, precision up to the nanosecond is supported by truncating extra digits.

Empty tables decoded in an interface{} create an empty initialized map[string]interface{}.

Types implementing the encoding.TextUnmarshaler interface are decoded from a TOML string.

When decoding a number, go-toml will return an error if the number is out of bounds for the target type (which includes negative numbers when decoding into an unsigned int).

If an error occurs while decoding the content of the document, this function returns a toml.DecodeError, providing context about the issue. When using strict mode and a field is missing, a `toml.StrictMissingError` is returned. In any other case, this function returns a standard Go error.

Type mapping

List of supported TOML types and their associated accepted Go types:

String           -> string
Integer          -> uint*, int*, depending on size
Float            -> float*, depending on size
Boolean          -> bool
Offset Date-Time -> time.Time
Local Date-time  -> LocalDateTime, time.Time
Local Date       -> LocalDate, time.Time
Local Time       -> LocalTime, time.Time
Array            -> slice and array, depending on elements types
Table            -> map and struct
Inline Table     -> same as Table
Array of Tables  -> same as Array and Table

func (*Decoder) DisallowUnknownFields

func (d *Decoder) DisallowUnknownFields() *Decoder

DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains a key that does not match a non-ignored field.

In that case, the Decoder returns a StrictMissingError that can be used to retrieve the individual errors as well as generate a human readable description of the missing fields.

Example
package main

import (
	"errors"
	"fmt"
	"strings"

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

func main() {
	type S struct {
		Key1 string
		Key3 string
	}
	doc := `
key1 = "value1"
key2 = "value2"
key3 = "value3"
`
	r := strings.NewReader(doc)
	d := toml.NewDecoder(r)
	d.DisallowUnknownFields()
	s := S{}
	err := d.Decode(&s)

	fmt.Println(err.Error())

	var details *toml.StrictMissingError
	if !errors.As(err, &details) {
		panic(fmt.Sprintf("err should have been a *toml.StrictMissingError, but got %s (%T)", err, err))
	}

	fmt.Println(details.String())
}
Output:
strict mode: fields in the document are missing in the target struct
2| key1 = "value1"
3| key2 = "value2"
 | ~~~~ unknown field
4| key3 = "value3"

func (*Decoder) EnableUnmarshalerInterface added in v2.2.0

func (d *Decoder) EnableUnmarshalerInterface() *Decoder

EnableUnmarshalerInterface allows to enable unmarshaler interface.

With this feature enabled, types implementing the unstable.Unmarshaler interface can be decoded from any structure of the document. It allows types that don't have a straightforward TOML representation to provide their own decoding logic.

The UnmarshalTOML method receives raw TOML bytes:

  • For single values: the raw value bytes (e.g., `"hello"` for a string)
  • For tables: all key-value lines belonging to that table
  • For inline tables/arrays: the raw bytes of the inline structure

The unstable.RawMessage type can be used to capture raw TOML bytes for later processing, similar to json.RawMessage.

*Unstable:* This method does not follow the compatibility guarantees of semver. It can be changed or removed without a new major version being issued.

Example (DynamicConfig)

This example demonstrates dynamic unmarshaling based on a discriminator field. The pluginConfig type uses UnmarshalTOML to first read the "type" field, then decode the rest of the configuration based on that type. This pattern is useful for plugin systems or configuration that varies by type.

package main

import (
	"fmt"
	"strings"

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

// pluginConfig demonstrates how to implement dynamic unmarshaling
// based on a "type" field. This pattern is useful for plugin systems
// or polymorphic configuration.
type pluginConfig struct {
	Type   string
	Config any
}

func (p *pluginConfig) UnmarshalTOML(data []byte) error {

	var typeOnly struct {
		Type string `toml:"type"`
	}
	if err := toml.Unmarshal(data, &typeOnly); err != nil {
		return err
	}
	p.Type = typeOnly.Type

	switch typeOnly.Type {
	case "database":
		var cfg struct {
			Type string `toml:"type"`
			Host string `toml:"host"`
			Port int    `toml:"port"`
		}
		if err := toml.Unmarshal(data, &cfg); err != nil {
			return err
		}
		p.Config = map[string]any{"host": cfg.Host, "port": cfg.Port}
	case "cache":
		var cfg struct {
			Type string `toml:"type"`
			TTL  int    `toml:"ttl"`
		}
		if err := toml.Unmarshal(data, &cfg); err != nil {
			return err
		}
		p.Config = map[string]any{"ttl": cfg.TTL}
	}
	return nil
}

func main() {
	doc := `
[[plugins]]
type = "database"
host = "localhost"
port = 5432

[[plugins]]
type = "cache"
ttl = 300
`
	type Config struct {
		Plugins []pluginConfig `toml:"plugins"`
	}

	var cfg Config
	err := toml.NewDecoder(strings.NewReader(doc)).
		EnableUnmarshalerInterface().
		Decode(&cfg)
	if err != nil {
		panic(err)
	}

	for _, p := range cfg.Plugins {
		fmt.Printf("type=%s config=%v\n", p.Type, p.Config)
	}
}
Output:
type=database config=map[host:localhost port:5432]
type=cache config=map[ttl:300]
Example (RawMessage)

This example demonstrates using RawMessage to capture raw TOML bytes for later processing. RawMessage is similar to json.RawMessage - it delays decoding so you can inspect the raw content or decode it differently based on context.

package main

import (
	"fmt"
	"strings"

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

func main() {
	doc := `
[plugin]
name = "example"
version = "1.0"
enabled = true
`

	type Config struct {
		Plugin unstable.RawMessage `toml:"plugin"`
	}

	var cfg Config
	err := toml.NewDecoder(strings.NewReader(doc)).
		EnableUnmarshalerInterface().
		Decode(&cfg)
	if err != nil {
		panic(err)
	}

	// cfg.Plugin contains the raw TOML bytes
	fmt.Printf("Raw TOML captured:\n%s", cfg.Plugin)

	// You can later decode it into a specific type
	var plugin struct {
		Name    string `toml:"name"`
		Version string `toml:"version"`
		Enabled bool   `toml:"enabled"`
	}
	if err := toml.Unmarshal(cfg.Plugin, &plugin); err != nil {
		panic(err)
	}
	fmt.Printf("Decoded: name=%s version=%s enabled=%v\n",
		plugin.Name, plugin.Version, plugin.Enabled)

}
Output:
Raw TOML captured:
name = "example"
version = "1.0"
enabled = true
Decoded: name=example version=1.0 enabled=true

type Encoder

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

Encoder writes a TOML document to an output stream.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new Encoder that writes to w.

func (*Encoder) EnableMarshalerInterface added in v2.4.3

func (enc *Encoder) EnableMarshalerInterface() *Encoder

EnableMarshalerInterface enables the unstable.Marshaler interface.

With this feature enabled, types implementing the unstable.Marshaler interface emit their own raw TOML instead of being encoded structurally. It is the encoding counterpart of Decoder.EnableUnmarshalerInterface, and allows types such as unstable.RawMessage to round-trip raw TOML bytes.

The bytes returned by MarshalTOML are spliced into the document verbatim. The encoder parses them to decide between the valid positions:

  • bytes forming a single value are emitted inline, as in `key = <raw>`;
  • bytes forming key-value lines are emitted as the body of a `[key]` table;
  • at the document root, the bytes are emitted as the whole document: the encode counterpart of the decoder delivering the whole document to a root unstable.Unmarshaler.

An empty result is omitted from the output. Bytes that are not valid TOML for their position result in an error, as do bytes forming table content in a position where only a value is valid (an array element, an inline table, or a table forced inline). MarshalTOML can be called more than once for the same value during a single encode, so it must be deterministic.

*Unstable:* This method does not follow the compatibility guarantees of semver. It can be changed or removed without a new major version being issued.

Example
package main

import (
	"bytes"
	"fmt"

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

func main() {
	// A RawMessage captured (or hand-built) as raw TOML is spliced back into
	// the document verbatim.
	type Config struct {
		Plugin unstable.RawMessage `toml:"plugin"`
	}

	cfg := Config{
		Plugin: unstable.RawMessage("name = \"example\"\nversion = \"1.0\"\n"),
	}

	var buf bytes.Buffer
	err := toml.NewEncoder(&buf).
		EnableMarshalerInterface().
		Encode(cfg)
	if err != nil {
		panic(err)
	}
	fmt.Print(buf.String())

}
Output:
[plugin]
name = "example"
version = "1.0"

func (*Encoder) Encode

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

Encode writes a TOML representation of v to the stream.

If v cannot be represented to TOML it returns an error.

Encoding rules

A top level slice containing only maps or structs is encoded as [[table array]].

All slices not matching rule 1 are encoded as [array]. As a result, any map or struct they contain is encoded as an {inline table}.

Nil interfaces and nil pointers are not supported.

Keys in key-values always have one part.

Intermediate tables are always printed.

By default, strings are encoded as literal string, unless they contain either a newline character or a single quote. In that case they are emitted as quoted strings.

Unsigned integers larger than math.MaxInt64 cannot be encoded. Doing so results in an error. This rule exists because the TOML specification only requires parsers to support at least the 64 bits integer range. Allowing larger numbers would create non-standard TOML documents, which may not be readable (at best) by other implementations. To encode such numbers, a solution is a custom type that implements encoding.TextMarshaler.

When encoding structs, fields are encoded in order of definition, with their exact name.

Tables and array tables are separated by empty lines. However, consecutive subtables definitions are not. For example:

[top1]

[top2]
[top2.child1]

[[array]]

[[array]]
[array.child2]

Struct tags

The encoding of each public struct field can be customized by the format string in the "toml" key of the struct field's tag. This follows encoding/json's convention. The format string starts with the name of the field, optionally followed by a comma-separated list of options. The name may be empty in order to provide options without overriding the default name.

The "multiline" option emits strings as quoted multi-line TOML strings, and arrays with one element per line. For strings, it only takes effect when the value contains a newline; single-line values are emitted as regular strings. It has no effect on fields that would not be encoded as strings or arrays.

The "inline" option turns fields that would be emitted as tables into inline tables instead. It has no effect on other fields.

The "omitempty" option prevents empty values or groups from being emitted.

The "omitzero" option prevents zero values or groups from being emitted.

The "commented" option prefixes the value and all its children with a comment symbol.

In addition to the "toml" tag struct tag, a "comment" tag can be used to emit a TOML comment before the value being annotated. Comments are ignored inside inline tables. For array tables, the comment is only present before the first element of the array.

func (*Encoder) SetArraysMultiline

func (enc *Encoder) SetArraysMultiline(multiline bool) *Encoder

SetArraysMultiline forces the encoder to emit all arrays with one element per line.

This behavior can be controlled on an individual struct field basis with the multiline tag:

MyField `multiline:"true"`

func (*Encoder) SetIndentSymbol

func (enc *Encoder) SetIndentSymbol(s string) *Encoder

SetIndentSymbol defines the string that should be used for indentation. The provided string is repeated for each indentation level. Defaults to two spaces.

func (*Encoder) SetIndentTables

func (enc *Encoder) SetIndentTables(indent bool) *Encoder

SetIndentTables forces the encoder to intent tables and array tables.

func (*Encoder) SetMarshalJSONNumbers added in v2.3.0

func (enc *Encoder) SetMarshalJSONNumbers(indent bool) *Encoder

SetMarshalJSONNumbers forces the encoder to serialize `json.Number` as a float or integer instead of relying on TextMarshaler to emit a string.

*Unstable:* This method does not follow the compatibility guarantees of semver. It can be changed or removed without a new major version being issued.

func (*Encoder) SetTablesInline

func (enc *Encoder) SetTablesInline(inline bool) *Encoder

SetTablesInline forces the encoder to emit all tables inline.

This behavior can be controlled on an individual struct field basis with the inline tag:

MyField `toml:",inline"`

type Key

type Key []string

Key represents a TOML key as a sequence of key parts.

type LocalDate

type LocalDate struct {
	Year  int
	Month int
	Day   int
}

LocalDate represents a calendar day in no specific timezone.

func (LocalDate) AsTime

func (d LocalDate) AsTime(zone *time.Location) time.Time

AsTime converts d into a specific time instance at midnight in zone.

func (LocalDate) MarshalText

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

MarshalText returns RFC 3339 representation of d.

func (LocalDate) String

func (d LocalDate) String() string

String returns RFC 3339 representation of d.

func (*LocalDate) UnmarshalText

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

UnmarshalText parses b using RFC 3339 to fill d.

type LocalDateTime

type LocalDateTime struct {
	LocalDate
	LocalTime
}

LocalDateTime represents a time of a specific day in no specific timezone.

func (LocalDateTime) AsTime

func (d LocalDateTime) AsTime(zone *time.Location) time.Time

AsTime converts d into a specific time instance in zone.

func (LocalDateTime) MarshalText

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

MarshalText returns RFC 3339 representation of d.

func (LocalDateTime) String

func (d LocalDateTime) String() string

String returns RFC 3339 representation of d.

func (*LocalDateTime) UnmarshalText

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

UnmarshalText parses b using RFC 3339 to fill d.

type LocalTime

type LocalTime struct {
	Hour       int // Hour of the day: [0; 24[
	Minute     int // Minute of the hour: [0; 60[
	Second     int // Second of the minute: [0; 59]
	Nanosecond int // Nanoseconds within the second:  [0, 1000000000[
	Precision  int // Number of digits to display for Nanosecond.
}

LocalTime represents a time of day of no specific day in no specific timezone.

func (LocalTime) MarshalText

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

MarshalText returns RFC 3339 representation of d.

func (LocalTime) String

func (d LocalTime) String() string

String returns RFC 3339 representation of d. If d.Nanosecond and d.Precision are zero, the time won't have a nanosecond component. If d.Nanosecond > 0 but d.Precision = 0, then the minimum number of digits for nanoseconds is provided.

func (*LocalTime) UnmarshalText

func (d *LocalTime) UnmarshalText(b []byte) error

UnmarshalText parses b using RFC 3339 to fill d.

type StrictMissingError

type StrictMissingError struct {
	// One error per field that could not be found.
	Errors []DecodeError
}

StrictMissingError occurs in a TOML document that does not have a corresponding field in the target value. It contains all the missing fields in Errors.

Emitted by Decoder when DisallowUnknownFields() was called.

func (*StrictMissingError) Error

func (s *StrictMissingError) Error() string

Error returns the canonical string for this error.

func (*StrictMissingError) String

func (s *StrictMissingError) String() string

String returns a human readable description of all errors.

func (*StrictMissingError) Unwrap added in v2.3.0

func (s *StrictMissingError) Unwrap() []error

Unwrap returns wrapped decode errors

Implements errors.Join() interface.

Directories

Path Synopsis
cmd
gotoml-test-decoder command
Package gotoml-test-decoder is a minimal decoder program used to compare this library with other TOML implementations.
Package gotoml-test-decoder is a minimal decoder program used to compare this library with other TOML implementations.
gotoml-test-encoder command
Package gotoml-test-encoder is a minimal encoder program used to compare this library with other TOML implementations.
Package gotoml-test-encoder is a minimal encoder program used to compare this library with other TOML implementations.
jsontoml command
Package jsontoml is a program that converts JSON to TOML.
Package jsontoml is a program that converts JSON to TOML.
tomljson command
Package tomljson is a program that converts TOML to JSON.
Package tomljson is a program that converts TOML to JSON.
tomll command
Package tomll is a linter program for TOML.
Package tomll is a linter program for TOML.
tomltestgen command
tomltestgen retrieves a given version of the language-agnostic TOML test suite in https://github.com/BurntSushi/toml-test and generates go-toml unit tests.
tomltestgen retrieves a given version of the language-agnostic TOML test suite in https://github.com/BurntSushi/toml-test and generates go-toml unit tests.
internal
assert
Package assert provides assertion functions for unit testing.
Package assert provides assertion functions for unit testing.
cli
Package cli provides common functions for command-line programs.
Package cli provides common functions for command-line programs.
parserbridge
Package parserbridge exposes the unstable parser's non-AST scanners to the root toml package without making them part of the unstable public API.
Package parserbridge exposes the unstable parser's non-AST scanners to the root toml package without making them part of the unstable public API.
testsuite
Package testsuite provides helper functions for interoperating with the language-agnostic TOML test suite at github.com/BurntSushi/toml-test.
Package testsuite provides helper functions for interoperating with the language-agnostic TOML test suite at github.com/BurntSushi/toml-test.
tracker
Package tracker provides functions for keeping track of AST nodes.
Package tracker provides functions for keeping track of AST nodes.
Package ossfuzz provides a fuzzing target for OSS-Fuzz.
Package ossfuzz provides a fuzzing target for OSS-Fuzz.
Package unstable provides APIs that do not meet the backward compatibility guarantees yet.
Package unstable provides APIs that do not meet the backward compatibility guarantees yet.

Jump to

Keyboard shortcuts

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