-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueries.go
executable file
·80 lines (66 loc) · 1.54 KB
/
queries.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
package ginTestContext
import (
"errors"
"net/url"
"reflect"
"github.com/gin-gonic/gin"
)
var (
ErrUnsupportedQueryType = errors.New("unsupported query type")
)
type queries struct {
Queries interface{}
}
func (q *queries) SetQueries(queries interface{}) {
q.Queries = queries
}
func (q *queries) writeQueriesToContext(c *gin.Context) error {
if q.Queries == nil {
return nil
}
switch reflect.ValueOf(q.Queries).Kind() {
case reflect.Map:
return q.writeQueriesWithMap(c)
case reflect.Ptr, reflect.Struct:
return q.writeQueriesWithObject(c)
default:
return ErrUnsupportedQueryType
}
}
func (q *queries) writeQueriesWithMap(c *gin.Context) error {
queries, ok := q.Queries.(map[string]string)
if !ok {
return ErrUnsupportedQueryType
}
values := url.Values{}
for key, value := range queries {
values.Set(key, value)
}
c.Request.URL = &url.URL{RawQuery: values.Encode()}
return nil
}
func (q *queries) writeQueriesWithObject(c *gin.Context) error {
var value reflect.Value
switch reflect.ValueOf(q.Queries).Kind() {
case reflect.Ptr:
value = reflect.ValueOf(q.Queries).Elem()
if value.Kind() != reflect.Struct {
return ErrUnsupportedQueryType
}
case reflect.Struct:
value = reflect.ValueOf(q.Queries)
default:
return ErrUnsupportedQueryType
}
values := url.Values{}
for i := 0; i < value.NumField(); i++ {
field := value.Type().Field(i)
tag := field.Tag.Get("form")
if tag == "" {
continue
}
values.Set(tag, value.Field(i).String())
}
c.Request.URL = &url.URL{RawQuery: values.Encode()}
return nil
}