-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.go
47 lines (42 loc) · 1.01 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
package rest
import (
"net/http"
"reflect"
"strconv"
"strings"
"unsafe"
"github.com/fatih/structs"
"github.com/timoth-y/kicksware-api/cdn-service/core/meta"
)
func ParseOptions(r *http.Request) meta.ImageOptions {
o := &meta.ImageOptions{}
query := r.URL.Query()
properties := structs.Names(o)
for _, prop := range properties {
value := query.Get(strings.ToLower(prop))
if value == "" {
continue
}
field := reflect.ValueOf(o).Elem().FieldByName(prop)
switch field.Kind().String() {
case "string":
setPrivateField(field, value)
case "int", "float":
if num, err := strconv.ParseInt(value, 10, 32); err == nil {
setPrivateField(field, int(num))
}
case "bool":
if sign, err := strconv.ParseBool(value); err == nil {
setPrivateField(field, sign)
}
default:
setPrivateField(field, value)
}
}
return *o
}
func setPrivateField(field reflect.Value, value interface{}) {
reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).
Elem().
Set(reflect.ValueOf(value))
}