-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples_test.go
97 lines (79 loc) · 1.88 KB
/
examples_test.go
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
// Copyright (c) 2023, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rawconv
import (
"fmt"
"net/url"
"reflect"
"time"
"github.com/davecgh/go-spew/spew"
)
// Below example demonstrates how to unmarshal a raw string into a
// time.Duration type using Unmarshal.
func ExampleUnmarshal() {
var duration time.Duration
if err := Unmarshal("1h2m3s", &duration); err != nil {
panic(err)
}
fmt.Println(duration)
// Output: 1h2m3s
}
func ExampleMarshal() {
duration := time.Hour + (time.Minute * 2) + (time.Second * 3)
val, err := Marshal(duration)
if err != nil {
panic(err)
}
fmt.Println(val.String())
// Output: 1h2m3s
}
func ExampleUnmarshaler() {
var u Unmarshaler
var target *url.URL
if err := u.Unmarshal("https://example.com", reflect.ValueOf(&target)); err != nil {
panic(err)
}
fmt.Println(target.String())
// Output: https://example.com
}
func ExampleUnmarshaler_Unmarshal() {
var u Unmarshaler
u.ItemsSeparator = ";"
var list []string
if err := u.Unmarshal("foo;bar", reflect.ValueOf(&list)); err != nil {
panic(err)
}
fmt.Println(list)
// Output: [foo bar]
}
func ExampleMarshaler() {
var m Marshaler
target, _ := url.ParseRequestURI("https://example.com")
val, err := m.Marshal(reflect.ValueOf(target))
if err != nil {
panic(err)
}
fmt.Println(val.String())
// Output: https://example.com
}
func ExampleUnmarshaler_Register() {
type myType struct {
something string
}
var u Unmarshaler
u.Register(reflect.TypeOf(myType{}), func(val Value, dest any) error {
mt := dest.(*myType)
mt.something = val.String()
return nil
})
var target myType
if err := u.Unmarshal("some value", reflect.ValueOf(&target)); err != nil {
panic(err)
}
spew.Dump(target)
// Output:
// (rawconv.myType) {
// something: (string) (len=10) "some value"
// }
}