router/common.go

44 lines
977 B
Go
Raw Normal View History

2024-10-08 21:57:25 +00:00
package router
import (
"fmt"
"reflect"
)
type GenericValues map[string][]string
2024-10-08 22:04:57 +00:00
func (gv GenericValues) Parse(data any, tag string) (err error) {
2024-10-08 21:57:25 +00:00
if gv == nil {
gv = make(GenericValues)
}
d := reflect.ValueOf(data)
if d.Kind() != reflect.Struct {
2024-10-08 22:04:57 +00:00
err = fmt.Errorf("expected struct input for data")
return
2024-10-08 21:57:25 +00:00
}
for i := 0; i < d.NumField(); i++ {
key, ok := d.Type().Field(i).Tag.Lookup(tag)
if !ok || key == "" {
continue
}
v := make([]string, 0)
val := d.Field(i)
if val.Kind() == reflect.Pointer || val.Kind() == reflect.Interface {
val = val.Elem()
}
if val.Kind() == reflect.Slice || val.Kind() == reflect.Array {
for j := 0; j < val.Len(); j++ {
item := val.Index(j)
if item.Kind() == reflect.Pointer || item.Kind() == reflect.Interface {
item = item.Elem()
}
v = append(v, fmt.Sprintf("%s", item.Interface()))
}
} else {
v = append(v, fmt.Sprintf("%s", val.Interface()))
}
gv[key] = v
}
2024-10-08 22:04:57 +00:00
return
2024-10-08 21:57:25 +00:00
}