-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_option_test.go
77 lines (68 loc) · 1.43 KB
/
example_option_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 query_test
import (
"fmt"
"reflect"
"strings"
"github.com/zoncoen/query-go"
)
// Person represents a person.
type Person struct {
Name string `json:"name,omitempty"`
}
func ExampleCaseInsensitive() {
person := Person{
Name: "Alice",
}
q := query.New(query.CaseInsensitive()).Key("NAME")
name, _ := q.Extract(person)
fmt.Println(name)
// Output:
// Alice
}
func ExampleExtractByStructTag() {
person := Person{
Name: "Alice",
}
q := query.New(query.ExtractByStructTag("json")).Key("name")
name, _ := q.Extract(person)
fmt.Println(name)
// Output:
// Alice
}
func ExampleCustomExtractFunc() {
person := Person{
Name: "Alice",
}
q := query.New(
query.CustomExtractFunc(func(f query.ExtractFunc) query.ExtractFunc {
return func(v reflect.Value) (reflect.Value, bool) {
return reflect.ValueOf("Bob"), true
}
}),
).Key("name")
name, _ := q.Extract(person)
fmt.Println(name)
// Output:
// Bob
}
// getFieldNameByJSONTag returns the JSON field tag as field name if exists.
func getFieldNameByJSONTag(field reflect.StructField) string {
tag, ok := field.Tag.Lookup("json")
if ok {
strs := strings.Split(tag, ",")
return strs[0]
}
return field.Name
}
func ExampleCustomStructFieldNameGetter() {
person := Person{
Name: "Alice",
}
q := query.New(
query.CustomStructFieldNameGetter(getFieldNameByJSONTag),
).Key("name")
name, _ := q.Extract(person)
fmt.Println(name)
// Output:
// Alice
}