Files
interpres/example_test.go
T

102 lines
2.1 KiB
Go
Raw Normal View History

// Copyright (c) 2026 Petr Balvín <opensource@petrbalvin.org> (https://petrbalvin.org)
// SPDX-License-Identifier: MIT
package interpres_test
import (
"fmt"
"log"
"sourcedock.dev/petrbalvin/interpres/v2"
)
func ExampleParse() {
const doc = `
title = "interpres"
[server]
host = "127.0.0.1"
port = 9090
`
d, err := interpres.Parse([]byte(doc))
if err != nil {
log.Fatal(err)
}
for _, key := range d.Root().Keys() { // written order, not sorted
entry, _ := d.Root().Get(key)
fmt.Println(key, "=", entry.Value())
}
// Output:
// title = interpres
// server = map[host:127.0.0.1 port:9090]
}
func ExampleUnmarshal() {
type Config struct {
Host string `toml:"host"`
Port int `toml:"port"`
}
var cfg Config
err := interpres.Unmarshal([]byte("host = \"db\"\nport = 5432\n"), &cfg)
if err != nil {
log.Fatal(err)
}
fmt.Println(cfg.Host, cfg.Port)
// Output: db 5432
}
func ExampleMarshal() {
type Server struct {
Host string `toml:"host"`
Port int `toml:"port"`
}
type Config struct {
Title string `toml:"title"`
Server Server `toml:"server"`
}
out, err := interpres.Marshal(Config{
Title: "demo",
Server: Server{Host: "127.0.0.1", Port: 9090},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", out)
// Output:
// title = "demo"
//
// [server]
// host = "127.0.0.1"
// port = 9090
}
func ExampleNumbersAsLiterals() {
var tree map[string]any
err := interpres.Unmarshal([]byte("rate = 1_000\n"), &tree,
interpres.RejectUnknownFields(true),
interpres.NumbersAsLiterals(true))
if err != nil {
log.Fatal(err)
}
fmt.Println(tree["rate"], string(tree["rate"].(interpres.Number)))
// Output: 1_000 1_000
}
func ExampleInlineTables() {
type Config struct {
Title string `toml:"title"`
Extras map[string]string `toml:"extras,inline"`
}
out, err := interpres.Marshal(Config{Title: "demo", Extras: map[string]string{"b": "two", "a": "one"}},
interpres.Layout(interpres.LayoutKindDeclaration),
interpres.LiteralMultiline(80),
interpres.InlineTables(40))
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", out)
// Output:
// title = "demo"
// extras = {a = "one", b = "two"}
}