-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexamples_test.go
95 lines (78 loc) · 2.18 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
package senml_test
import (
"fmt"
"github.com/farshidtz/senml/v2/codec"
)
func Example_decodeValidateNormalizeEncode() {
input := `[{"bn":"room1/temp","u":"Cel","t":1276020076,"v":23.5},{"u":"Cel","t":1276020091,"v":23.6}]`
// decode JSON
pack, err := codec.DecodeJSON([]byte(input))
if err != nil {
panic(err) // handle the error
}
// validate the SenML Pack
err = pack.Validate()
if err != nil {
panic(err) // handle the error
}
// normalize the SenML Pack
pack.Normalize()
// encode the normalized SenML Pack to JSON
dataOut, err := codec.EncodeJSON(pack, codec.SetPrettyPrint)
if err != nil {
panic(err) // handle the error
}
fmt.Printf("%s", dataOut)
// Output:
// [
// {"n":"room1/temp","u":"Cel","t":1276020076,"v":23.5},
// {"n":"room1/temp","u":"Cel","t":1276020091,"v":23.6}
// ]
}
func ExamplePack_Normalize() {
input := `[{"bn":"room1/temp","u":"Cel","t":1276020076.305,"v":23.5},{"u":"Cel","t":1276020091.305,"v":23.6}]`
// decode JSON
pack, err := codec.DecodeJSON([]byte(input))
if err != nil {
panic(err) // handle the error
}
pack.Normalize()
dataOut, err := codec.EncodeJSON(pack, codec.SetPrettyPrint)
if err != nil {
panic(err) // handle the error
}
fmt.Printf("%s", dataOut)
// Output:
// [
// {"n":"room1/temp","u":"Cel","t":1276020076.305,"v":23.5},
// {"n":"room1/temp","u":"Cel","t":1276020091.305,"v":23.6}
// ]
}
func ExamplePack_Validate() {
input := `[{"bn":"room1/ temp","t":1270000040,"v":23.5},{"t":1270000050,"v":23.6}]`
// decode JSON
pack, err := codec.DecodeJSON([]byte(input))
if err != nil {
panic(err) // handle the error
}
// validate the SenML Pack
err = pack.Validate()
if err != nil {
fmt.Println(err) // handle the error
}
// Output: invalid name: must begin with alphanumeric and contain alphanumeric or one of - : . / _
}
func ExamplePack_Validate2() {
input := `[{"bn":"room1/temp","t":1270000050,"v":23.6,"vs":"cool"}]`
// decode JSON
pack, err := codec.DecodeJSON([]byte(input))
if err != nil {
panic(err) // handle the error
}
// validate the SenML Pack
err = pack.Validate()
if err != nil {
fmt.Println(err) // handle the error
}
// Output: too many values in single record
}