diff --git a/go.mod b/go.mod index cdc2352..b70ec7a 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module git.gsuntres.com/general/commons go 1.25.0 require ( + github.com/go-viper/mapstructure/v2 v2.5.0 github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5 go.mongodb.org/mongo-driver/v2 v2.5.0 ) diff --git a/go.sum b/go.sum index 7c17640..40a8c23 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= +github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5 h1:x2QxKV4w/sBEwwUUmBH/8cFjeOBZqwaB5dz5rcuFspU= diff --git a/struct.go b/struct.go index 8420822..1810bf6 100644 --- a/struct.go +++ b/struct.go @@ -4,10 +4,15 @@ import ( "log" "reflect" "strings" - + + "github.com/go-viper/mapstructure/v2" "go.mongodb.org/mongo-driver/v2/bson" ) +func StructToStruct(source any, target any) { + mapstructure.Decode(source, &target) +} + // 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 { diff --git a/struct_test.go b/struct_test.go index f145485..02283f0 100644 --- a/struct_test.go +++ b/struct_test.go @@ -4,6 +4,28 @@ import ( "testing" ) +func TestStructToStruct(t *testing.T) { + type O struct { + Name string + Age int + Active bool + } + + o := &O{ + Name: "Nick", + Age: 15, + Active: true, + } + + var oo O + + StructToStruct(o, &oo) + + if oo.Name != "Nick" || oo.Age != 15 || !oo.Active { + t.Fatalf("failed to copy %v", oo) + } +} + func TestStructToMapRecursive(t *testing.T) { type O struct { Name string