-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathconverter.go
More file actions
51 lines (45 loc) · 988 Bytes
/
converter.go
File metadata and controls
51 lines (45 loc) · 988 Bytes
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
package main
import (
"fmt"
"github.com/hetiansu5/urlquery"
"reflect"
"strconv"
)
// An EncodeData is test structure
type EncodeData struct {
Id int `query:"id"`
Name string `query:"name"`
}
func main() {
data := EncodeData{
Id: 2,
Name: "Nick",
}
encoder := urlquery.NewEncoder()
encoder.RegisterEncodeFunc(reflect.String, func(rv reflect.Value) string {
return rv.String() + "Will"
})
//Marshal: from go structure to url query string
bytes, err := encoder.Marshal(data)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bytes))
//Unmarshal: from url query string to go structure
parser := urlquery.NewParser()
parser.RegisterDecodeFunc(reflect.Int, func(s string) (reflect.Value, error) {
i, err := strconv.Atoi(s)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(i + 10), nil
})
v := &EncodeData{}
err = parser.Unmarshal(bytes, v)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(*v)
}