-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathwithoption.go
More file actions
76 lines (65 loc) · 1.45 KB
/
withoption.go
File metadata and controls
76 lines (65 loc) · 1.45 KB
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
package main
import (
"fmt"
"github.com/hetiansu5/urlquery"
"net/url"
)
// A OptionChild is test structure
type OptionChild struct {
Status bool `query:"status"`
Name string
}
// An OptionData is test structure
type OptionData struct {
Id int
Name string `query:"name"`
Child OptionChild `query:"c"`
Params map[string]int8 `query:"p"`
Slice []OptionChild
}
// A SelfQueryEncoder is test structure
type SelfQueryEncoder struct{}
// Escape is test func
func (u SelfQueryEncoder) Escape(s string) string {
return url.QueryEscape(s)
}
// UnEscape is test func
func (u SelfQueryEncoder) UnEscape(s string) (string, error) {
return url.QueryUnescape(s)
}
func main() {
data := OptionData{
Id: 2,
Name: "test",
Child: OptionChild{
Status: true,
},
Params: map[string]int8{
"one": 1,
"two": 2,
},
Slice: []OptionChild{
{Status: true},
{Name: "honey"},
},
}
fmt.Println(data)
//Marshal: from go structure to http-query string
builder := urlquery.NewEncoder(urlquery.WithNeedEmptyValue(true),
urlquery.WithQueryEncoder(SelfQueryEncoder{}))
bytes, err := builder.Marshal(data)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bytes))
//Unmarshal: from http-query string to go structure
v := &OptionData{}
parser := urlquery.NewParser(urlquery.WithQueryEncoder(SelfQueryEncoder{}))
err = parser.Unmarshal(bytes, v)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(*v)
}