-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.go
70 lines (51 loc) · 1.3 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
/*
Params create url encoded strings from structs
Supported field types: string, int, float
*/
package params
import(
"net/url"
"reflect"
"errors"
"strconv"
"log"
)
func Encode(s interface{}) (string, error) {
if reflect.TypeOf(s).Kind() != reflect.Struct {
// return "", errors.New("Cannot encode non-struct: " + string(reflect.TypeOf(s).Kind()))
}
values := reflect.ValueOf(s).Elem()
types := values.Type()
uv := url.Values{}
for i := 0; i < values.NumField(); i++ {
fieldValue := values.Field(i)
fieldType := types.Field(i)
tag := fieldType.Tag.Get("param")
if tag == "_" { continue }
if fieldType.PkgPath == "" {
var value string = ""
kind := fieldValue.Kind()
switch kind {
case reflect.String:
value = fieldValue.String()
break
case reflect.Int:
fallthrough
case reflect.Int64:
value = strconv.FormatInt(fieldValue.Int(), 10)
break
case reflect.Float32:
value = strconv.FormatFloat(fieldValue.Float(), 'f', -1, 32)
break
case reflect.Float64:
value = strconv.FormatFloat(fieldValue.Float(), 'f', -1, 64)
break
default:
log.Println(kind)
return "", errors.New("Data type not supported: " + string(kind))
}
uv.Add(tag, value)
}
}
return uv.Encode(), nil
}