1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
package main
import (
"fmt"
"os"
"reflect"
"sort"
"strings"
"time"
"github.com/BurntSushi/toml"
)
type (
example struct {
Title string
Desc string
Integers []int
Floats []float64
Times []fmtTime
Duration []time.Duration
Distros []distro
Servers map[string]server
Characters map[string][]struct {
Name string
Rank string
}
}
server struct {
IP string
Hostname string
Enabled bool
}
distro struct {
Name string
Packages string
}
fmtTime struct{ time.Time }
)
func (t fmtTime) String() string {
f := "2006-01-02 15:04:05.999999999"
if t.Time.Hour() == 0 {
f = "2006-01-02"
}
if t.Time.Year() == 0 {
f = "15:04:05.999999999"
}
if t.Time.Location() == time.UTC {
f += " UTC"
} else {
f += " -0700"
}
return t.Time.Format(`"` + f + `"`)
}
func main() {
f := "example.toml"
if _, err := os.Stat(f); err != nil {
f = "_example/example.toml"
}
var config example
meta, err := toml.DecodeFile(f, &config)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
indent := strings.Repeat(" ", 14)
fmt.Print("Decoded")
typ, val := reflect.TypeOf(config), reflect.ValueOf(config)
for i := 0; i < typ.NumField(); i++ {
indent := indent
if i == 0 {
indent = strings.Repeat(" ", 7)
}
fmt.Printf("%s%-11s → %v\n", indent, typ.Field(i).Name, val.Field(i).Interface())
}
fmt.Print("\nKeys")
keys := meta.Keys()
sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
for i, k := range keys {
indent := indent
if i == 0 {
indent = strings.Repeat(" ", 10)
}
fmt.Printf("%s%-10s %s\n", indent, meta.Type(k...), k)
}
fmt.Print("\nUndecoded")
keys = meta.Undecoded()
sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
for i, k := range keys {
indent := indent
if i == 0 {
indent = strings.Repeat(" ", 5)
}
fmt.Printf("%s%-10s %s\n", indent, meta.Type(k...), k)
}
}
|