-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexample_self_marshal_test.go
77 lines (63 loc) · 2.19 KB
/
example_self_marshal_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
package qs_test
import (
"encoding/hex"
"fmt"
"github.com/pasztorpisti/qs"
)
// This example shows how to implement the MarshalQS and UnmarshalQS interfaces
// with a custom type that wants to handle its own marshaling and unmarshaling.
func Example_selfMarshalingType() {
// Using the []byte type with its default marshaling.
defaultMarshaling()
// Using the Byte array type that implements custom marshaling.
customMarshaling()
// Output:
// Default-Marshal-Result: a=0&a=1&a=2&b=3&b=4&b=5 <nil>
// Default-Unmarshal-Result: len=2 a=[0 1 2] b=[3 4 5] <nil>
// Custom-Marshal-Result: a=000102&b=030405 <nil>
// Custom-Unmarshal-Result: len=2 a=[0 1 2] b=[3 4 5] <nil>
}
func defaultMarshaling() {
queryStr, err := qs.Marshal(map[string][]byte{
"a": {0, 1, 2},
"b": {3, 4, 5},
})
fmt.Println("Default-Marshal-Result:", queryStr, err)
var query map[string][]byte
err = qs.Unmarshal(&query, queryStr)
fmt.Printf("Default-Unmarshal-Result: len=%v a=%v b=%v %v\n",
len(query), query["a"], query["b"], err)
}
func customMarshaling() {
queryStr, err := qs.Marshal(map[string]Bytes{
"a": {0, 1, 2},
"b": {3, 4, 5},
})
fmt.Println("Custom-Marshal-Result:", queryStr, err)
var query map[string]Bytes
err = qs.Unmarshal(&query, queryStr)
fmt.Printf("Custom-Unmarshal-Result: len=%v a=%v b=%v %v\n",
len(query), query["a"], query["b"], err)
}
// Bytes implements the MarshalQS and the UnmarshalQS interfaces to marshal
// itself as a hex string instead of the usual array serialisation used in
// standard query strings.
//
// The default marshaler marshals the []byte{4, 2} array to the "key=4&key=2"
// query string. In contrast the Bytes{4, 2} array is marshaled as "key=0402".
type Bytes []byte
func (b Bytes) MarshalQS(opts *qs.MarshalOptions) ([]string, error) {
return []string{hex.EncodeToString(b)}, nil
}
func (b *Bytes) UnmarshalQS(a []string, opts *qs.UnmarshalOptions) error {
s, err := opts.SliceToString(a)
if err != nil {
return err
}
*b, err = hex.DecodeString(s)
return err
}
// Compile time check: Bytes implements the qs.MarshalQS interface.
var _ qs.MarshalQS = Bytes{}
// Compile time check: *Bytes implements the qs.UnmarshalQS interface.
var _ qs.UnmarshalQS = &Bytes{}