Add jsonschema Validate

This commit is contained in:
George Suntres
2026-03-29 12:01:48 -04:00
parent ebdf370c23
commit 434ecef67a
6 changed files with 164 additions and 3 deletions

View File

@@ -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)