-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
116 lines (106 loc) · 2.11 KB
/
example_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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Copyright (c) 2021 the SC authors. All rights reserved. MIT License.
package sc_test
import (
"fmt"
"github.com/sc-lang/go-sc"
"github.com/sc-lang/go-sc/scparse"
)
func ExampleUnmarshal() {
scData := []byte(`{
name: "foo"
memory: 256
required: true
}`)
type Config struct {
Name string `sc:"name"`
Memory int `sc:"memory"`
IsRequired bool `sc:"required"`
}
var config Config
err := sc.Unmarshal(scData, &config)
if err != nil {
fmt.Printf("error: %v\n", err)
}
fmt.Printf("%+v\n", config)
// Output:
// {Name:foo Memory:256 IsRequired:true}
}
func ExampleUnmarshal_variables() {
scData := []byte(`{
code: ${id}
path: "/home/${user}/data"
}`)
type Config struct {
Code int `sc:"code"`
Path string `sc:"path"`
}
var config Config
vars := sc.MustVariables(map[string]interface{}{
"id": 145,
"user": "ted",
})
err := sc.Unmarshal(scData, &config, sc.WithVariables(vars))
if err != nil {
fmt.Printf("error: %v\n", err)
}
fmt.Printf("%+v\n", config)
// Output:
// {Code:145 Path:/home/ted/data}
}
func ExampleUnmarshalNode() {
scData := []byte(`{
name: "test"
ports: [
{ src: 8080, dst: 8080 }
{ src: 80, dst: 80 }
]
}`)
type Config struct {
Name string
Ports scparse.ValueNode
}
var config Config
err := sc.Unmarshal(scData, &config)
if err != nil {
fmt.Printf("error: %v\n", err)
}
// Can inspect node
fmt.Printf("%v\n", config.Ports.Type())
// Finish the unmarshaling process
type Port struct {
Src int
Dst int
}
var ports []Port
err = sc.UnmarshalNode(config.Ports, &ports)
if err != nil {
fmt.Printf("error: %v\n", err)
}
fmt.Printf("%+v\n", ports)
// Output:
// List
// [{Src:8080 Dst:8080} {Src:80 Dst:80}]
}
func ExampleMarshal() {
type Config struct {
Name string `sc:"name"`
Memory int `sc:"memory"`
IsRequired bool `sc:"required"`
}
config := Config{
Name: "foo",
Memory: 256,
IsRequired: true,
}
b, err := sc.Marshal(config)
if err != nil {
fmt.Printf("error: %v\n", err)
}
fmt.Printf("%s\n", b)
// Output:
// {
// name: "foo"
// memory: 256
// required: true
// }
}