router/common.go
2024-10-08 17:57:25 -04:00

42 lines
949 B
Go

package router
import (
"fmt"
"reflect"
)
type GenericValues map[string][]string
func (gv GenericValues) Parse(data any, tag string) {
if gv == nil {
gv = make(GenericValues)
}
d := reflect.ValueOf(data)
if d.Kind() != reflect.Struct {
panic(fmt.Errorf("expected struct input for data"))
}
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
}
}