docs: add godoc examples, extend the basic example and map encoding/json
Test / test (push) Successful in 1m47s
Test / test (push) Successful in 1m47s
Assisted-by: GLM 5.3 Flash
This commit is contained in:
+103
@@ -0,0 +1,103 @@
|
||||
// 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 ExampleDecoder() {
|
||||
var tree map[string]any
|
||||
err := interpres.NewDecoder().
|
||||
DisallowUnknownFields().
|
||||
UseNumber().
|
||||
Decode([]byte("rate = 1_000\n"), &tree)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(tree["rate"], string(tree["rate"].(interpres.Number)))
|
||||
// Output: 1_000 1_000
|
||||
}
|
||||
|
||||
func ExampleEncoder() {
|
||||
type Config struct {
|
||||
Title string `toml:"title"`
|
||||
Extras map[string]string `toml:"extras,inline"`
|
||||
}
|
||||
out, err := interpres.NewEncoder().
|
||||
Layout(interpres.LayoutKindDeclaration).
|
||||
LiteralMultiline(80).
|
||||
InlineTables(40).
|
||||
Marshal(Config{Title: "demo", Extras: map[string]string{"b": "two", "a": "one"}})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Printf("%s", out)
|
||||
// Output:
|
||||
// title = "demo"
|
||||
// extras = {a = "one", b = "two"}
|
||||
}
|
||||
Reference in New Issue
Block a user