package toml
import "github.com/pelletier/go-toml/v2"
Package toml is a library to read and write TOML documents.
Index ¶
- func Marshal(v interface{}) ([]byte, error)
- func Unmarshal(data []byte, v interface{}) error
- type DecodeError
- func (e *DecodeError) Error() string
- func (e *DecodeError) Key() Key
- func (e *DecodeError) Position() (row int, column int)
- func (e *DecodeError) String() string
- type Decoder
- func NewDecoder(r io.Reader) *Decoder
- func (d *Decoder) Decode(v interface{}) error
- func (d *Decoder) SetStrict(strict bool)
- type Encoder
- func NewEncoder(w io.Writer) *Encoder
- func (enc *Encoder) Encode(v interface{}) error
- func (enc *Encoder) SetArraysMultiline(multiline bool)
- func (enc *Encoder) SetIndentSymbol(s string)
- func (enc *Encoder) SetIndentTables(indent bool)
- func (enc *Encoder) SetTablesInline(inline bool)
- type Key
- type LocalDate
- func LocalDateOf(t time.Time) LocalDate
- func ParseLocalDate(s string) (LocalDate, error)
- func (d LocalDate) AddDays(n int) LocalDate
- func (d LocalDate) After(past LocalDate) bool
- func (d LocalDate) Before(future LocalDate) bool
- func (d LocalDate) DaysSince(s LocalDate) (days int)
- func (d LocalDate) In(loc *time.Location) time.Time
- func (d LocalDate) IsValid() bool
- func (d LocalDate) MarshalText() ([]byte, error)
- func (d LocalDate) String() string
- func (d *LocalDate) UnmarshalText(data []byte) error
- type LocalDateTime
- func LocalDateTimeOf(t time.Time) LocalDateTime
- func ParseLocalDateTime(s string) (LocalDateTime, error)
- func (dt LocalDateTime) After(past LocalDateTime) bool
- func (dt LocalDateTime) Before(future LocalDateTime) bool
- func (dt LocalDateTime) In(loc *time.Location) time.Time
- func (dt LocalDateTime) IsValid() bool
- func (dt LocalDateTime) MarshalText() ([]byte, error)
- func (dt LocalDateTime) String() string
- func (dt *LocalDateTime) UnmarshalText(data []byte) error
- type LocalTime
- func LocalTimeOf(t time.Time) LocalTime
- func ParseLocalTime(s string) (LocalTime, error)
- func (t LocalTime) IsValid() bool
- func (t LocalTime) MarshalText() ([]byte, error)
- func (t LocalTime) String() string
- func (t *LocalTime) UnmarshalText(data []byte) error
- type StrictMissingError
Examples ¶
Functions ¶
func Marshal ¶
Marshal serializes a Go value as a TOML document.
It is a shortcut for Encoder.Encode() with the default options.
Code:
Output:Example¶
{
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']
}
Version = 2
Name = 'go-toml'
Tags = ['go', 'toml']
func Unmarshal ¶
Unmarshal deserializes a TOML document into a Go value.
It is a shortcut for Decoder.Decode() with the default options.
Code:
Output:Example¶
{
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]
}
version: 2
name: go-toml
tags: [go toml]
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.
Code:
Output:Example¶
{
doc := `name = 123__456`
s := map[string]interface{}{}
err := Unmarshal([]byte(doc), &s)
fmt.Println(err)
//nolint:errorlint
de := err.(*DecodeError)
fmt.Println(de.String())
row, col := de.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
}
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. The key is present only if this DecodeError is part of a StrictMissingError.
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 ¶
NewDecoder creates a new Decoder that will read from r.
func (*Decoder) Decode ¶
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.SetStrict() 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 approriate Local* structure is used.
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).
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) SetStrict ¶
SetStrict toggles decoding in stict mode.
When the decoder is in strict mode, it will record fields from the document
that could not be set on the target value. 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.
Code:
Output:Example¶
{
type S struct {
Key1 string
Key3 string
}
doc := `
key1 = "value1"
key2 = "value2"
key3 = "value3"
`
r := strings.NewReader(doc)
d := toml.NewDecoder(r)
d.SetStrict(true)
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"
// | ~~~~ missing field
// 4| key3 = "value3"
}
strict mode: fields in the document are missing in the target struct
2| key1 = "value1"
3| key2 = "value2"
| ~~~~ missing field
4| key3 = "value3"
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder writes a TOML document to an output stream.
func NewEncoder ¶
NewEncoder returns a new Encoder that writes to w.
func (*Encoder) Encode ¶
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.
When encoding structs, fields are encoded in order of definition, with their exact name.
Struct tags
The following struct tags are available to tweak encoding on a per-field basis:
toml:"foo" Changes the name of the key to use for the field to foo. multiline:"true" When the field contains a string, it will be emitted as a quoted multi-line TOML string. inline:"true" When the field would normally be encoded as a table, it is instead encoded as an inline table.
func (*Encoder) SetArraysMultiline ¶
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 ¶
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 ¶
SetIndentTables forces the encoder to intent tables and array tables.
func (*Encoder) SetTablesInline ¶
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 `inline:"true"`
type Key ¶
type Key []string
type LocalDate ¶
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 ¶
LocalDateOf returns the LocalDate in which a time occurs in that time's location.
func ParseLocalDate ¶
ParseLocalDate parses a string in RFC3339 full-date format and returns the date value it represents.
func (LocalDate) AddDays ¶
AddDays returns the date that is n days in the future. n can also be negative to go into the past.
func (LocalDate) After ¶
After reports whether d1 occurs after past date.
func (LocalDate) Before ¶
Before reports whether d1 occurs before future date.
func (LocalDate) DaysSince ¶
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 ¶
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 ¶
IsValid reports whether the date is valid.
func (LocalDate) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface. The output is the result of d.String().
func (LocalDate) String ¶
String returns the date in RFC3339 full-date format.
func (*LocalDate) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface. The date is expected to be a string in a format accepted by ParseLocalDate.
type LocalDateTime ¶
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 ¶
func LocalDateTimeOf(t time.Time) LocalDateTime
LocalDateTimeOf returns the LocalDateTime in which a time occurs in that time's location.
func ParseLocalDateTime ¶
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 ¶
func (dt LocalDateTime) After(past LocalDateTime) bool
After reports whether dt occurs after past.
func (LocalDateTime) Before ¶
func (dt LocalDateTime) Before(future LocalDateTime) bool
Before reports whether dt occurs before future.
func (LocalDateTime) In ¶
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 ¶
func (dt LocalDateTime) IsValid() bool
IsValid reports whether the datetime is valid.
func (LocalDateTime) MarshalText ¶
func (dt LocalDateTime) MarshalText() ([]byte, error)
MarshalText implements the encoding.TextMarshaler interface. The output is the result of dt.String().
func (LocalDateTime) String ¶
func (dt LocalDateTime) String() string
String returns the date in the format described in ParseLocalDate.
func (*LocalDateTime) UnmarshalText ¶
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 ¶
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 ¶
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 ¶
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 ¶
IsValid reports whether the time is valid.
func (LocalTime) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface. The output is the result of t.String().
func (LocalTime) 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 ¶
UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be a string in a format accepted by ParseLocalTime.
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 SetStrict(true) 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.
Source Files ¶
decode.go doc.go errors.go localtime.go marshaler.go parser.go scanner.go strict.go targets.go unmarshaler.go
Directories ¶
Path | Synopsis |
---|---|
benchmark | |
internal |
- Version
- v2.0.0-beta.2
- Published
- May 11, 2021
- Platform
- windows/amd64
- Imports
- 16 packages
- Last checked
- now –
Tools for package owners.