Add jsonschema Validate
This commit is contained in:
44
struct.go
44
struct.go
@@ -4,10 +4,50 @@ import (
|
||||
"log"
|
||||
"reflect"
|
||||
"strings"
|
||||
// "encoding/json"
|
||||
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
)
|
||||
|
||||
// StructToMapRecursive given a struct or a primitive will return the equivalent
|
||||
// map[string]any of the struct or the primitive as is.
|
||||
func StructToMapRecursive(obj any) any {
|
||||
v := reflect.ValueOf(obj)
|
||||
|
||||
// Handle pointers by getting the underlying element
|
||||
if v.Kind() == reflect.Ptr {
|
||||
if v.IsNil() { return nil }
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Struct:
|
||||
result := make(map[string]any)
|
||||
t := v.Type()
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
// Skip unexported fields (private fields)
|
||||
if field.PkgPath != "" { continue }
|
||||
|
||||
// Recurse into the field's value
|
||||
result[field.Name] = StructToMapRecursive(v.Field(i).Interface())
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
case reflect.Slice, reflect.Array:
|
||||
result := make([]any, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
result[i] = StructToMapRecursive(v.Index(i).Interface())
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
default:
|
||||
// Return basic types (int, string, etc.) as is
|
||||
return obj
|
||||
}
|
||||
}
|
||||
|
||||
// MapToStruct will convert a map[string]any to a struct.
|
||||
func MapToStruct(m map[string]any, o any) error {
|
||||
b, err := bson.Marshal(m)
|
||||
|
||||
Reference in New Issue
Block a user