-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparams.go
71 lines (61 loc) · 1.52 KB
/
params.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
package ginTestContext
import (
"errors"
"github.com/gin-gonic/gin"
"reflect"
)
var (
ErrUnsupportedURIParamType = errors.New("unsupported uri param type")
)
type uriParams struct {
URIParams interface{}
}
func (u *uriParams) SetURIParams(uriParams interface{}) {
u.URIParams = uriParams
}
func (u *uriParams) writeURIParamsToContext(c *gin.Context) error {
if u.URIParams == nil {
return nil
}
switch reflect.ValueOf(u.URIParams).Kind() {
case reflect.Map:
return u.writeURIParamsWithMap(c)
case reflect.Ptr, reflect.Struct:
return u.writeURIParamsWithObject(c)
default:
return ErrUnsupportedURIParamType
}
}
func (u *uriParams) writeURIParamsWithMap(c *gin.Context) error {
uriParams, ok := u.URIParams.(map[string]string)
if !ok {
return ErrUnsupportedURIParamType
}
for key, value := range uriParams {
c.Params = append(c.Params, gin.Param{Key: key, Value: value})
}
return nil
}
func (u *uriParams) writeURIParamsWithObject(c *gin.Context) error {
var value reflect.Value
switch reflect.ValueOf(u.URIParams).Kind() {
case reflect.Ptr:
value = reflect.ValueOf(u.URIParams).Elem()
if value.Kind() != reflect.Struct {
return ErrUnsupportedURIParamType
}
case reflect.Struct:
value = reflect.ValueOf(u.URIParams)
default:
return ErrUnsupportedURIParamType
}
for i := 0; i < value.NumField(); i++ {
field := value.Type().Field(i)
tag := field.Tag.Get("uri")
if tag == "" {
continue
}
c.Params = append(c.Params, gin.Param{Key: tag, Value: value.Field(i).String()})
}
return nil
}