mirror of
https://github.com/wonli/aqi.git
synced 2025-10-06 17:16:50 +08:00
init
This commit is contained in:
30
utils/struct2map.go
Normal file
30
utils/struct2map.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func StructToMap(input any) map[string]any {
|
||||
out := make(map[string]any)
|
||||
v := reflect.ValueOf(input)
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
// we only accept structs
|
||||
if v.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
|
||||
typ := v.Type()
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
fi := typ.Field(i)
|
||||
// skip unexported fields
|
||||
if fi.PkgPath != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
out[fi.Name] = v.Field(i).Interface()
|
||||
}
|
||||
return out
|
||||
}
|
Reference in New Issue
Block a user