File: example_marshaler_rec_test.go

package info (click to toggle)
golang-github-naoina-toml 0.1.1-8
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 416 kB
  • sloc: makefile: 7
file content (72 lines) | stat: -rw-r--r-- 1,651 bytes parent folder | download | duplicates (2)
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
package toml_test

import (
	"errors"
	"fmt"
	"net"
	"time"

	"github.com/naoina/toml"
)

// This example shows how the UnmarshalerRec interface can be used to apply field
// validations and default values.

type Server struct {
	Addr    string        // "<host>:<port>"
	Timeout time.Duration // defaults to 10s
}

// UnmarshalTOML implements toml.Unmarshaler.
func (s *Server) UnmarshalTOML(decode func(interface{}) error) error {
	// Parse the input into type tomlServer, which defines the
	// expected format of Server in TOML.
	type tomlServer struct {
		Addr    string
		Timeout string
	}
	var dec tomlServer
	if err := decode(&dec); err != nil {
		return err
	}

	// Validate the address.
	if dec.Addr == "" {
		return errors.New("missing server address")
	}
	_, _, err := net.SplitHostPort(dec.Addr)
	if err != nil {
		return fmt.Errorf("invalid server address %q: %v", dec.Addr, err)
	}
	// Validate the timeout and apply the default value.
	var timeout time.Duration
	if dec.Timeout == "" {
		timeout = 10 * time.Second
	} else if timeout, err = time.ParseDuration(dec.Timeout); err != nil {
		return fmt.Errorf("invalid server timeout %q: %v", dec.Timeout, err)
	}

	// Assign the decoded value.
	*s = Server{Addr: dec.Addr, Timeout: timeout}
	return nil
}

func ExampleUnmarshalerRec() {
	input := []byte(`
[[servers]]
addr = "198.51.100.3:80"

[[servers]]
addr = "192.0.2.10:8080"
timeout = "30s"
`)
	var config struct {
		Servers []Server
	}
	toml.Unmarshal(input, &config)
	fmt.Printf("Unmarshaled:\n%+v\n\n", config)

	// Output:
	// Unmarshaled:
	// {Servers:[{Addr:198.51.100.3:80 Timeout:10s} {Addr:192.0.2.10:8080 Timeout:30s}]}
}