diff --git a/issue_7_test.go b/issue_7_test.go index 7eb118b001fdb35f5aebd26d95c95ea2ad8c1175..4b6bf622a08af8d0e73ded83ba6b437a0cd3e361 100644 --- a/issue_7_test.go +++ b/issue_7_test.go @@ -45,3 +45,48 @@ func TestSetValue(t *testing.T) { assert.Equal(t, v, nv) } + +type Issue7Routing struct { + P PathValue `json:"p" yaml:"p"` + X string `json:"x" yaml:"x"` +} + +type Issue7Server struct { + Routing []Issue7Routing `json:"routing" yaml:"routing"` +} + +type Issue7Config struct { + Server Issue7Server `json:"server" yaml:"server"` +} + +func TestPathRewrite(t *testing.T) { + + obj := Issue7Config{ + Server: Issue7Server{ + Routing: []Issue7Routing{ + { + P: "./test", + X: "testX", + }, + }, + }, + } + + v, err := GetValue[*Issue7Config](&obj, "Server.Routing.0.P") + assert.Nil(t, err) + + assert.Equal(t, v, PathValue("./test")) + + nv := PathValue("newValue") + err = SetValue[*Issue7Config](&obj, "Server.Routing.0.P", nv) + assert.Nil(t, err) + + if obj.Server.Routing[0].P != "newValue" { + t.Fatalf("expected newValue, got: %s", obj.Server.Routing[0].P) + } + + v, err = GetValue[*Issue7Config](&obj, "Server.Routing.0.P") + assert.Nil(t, err) + assert.Equal(t, v, nv) + +} diff --git a/set.go b/set.go index 1c1a387e62734d9361286e3fd1d1757285082b65..8004d051a926312633de027306a3a0f6f733a28d 100644 --- a/set.go +++ b/set.go @@ -85,6 +85,19 @@ func SetValue[D any](obj D, keyWithDots string, newValue any) error { switch v.Elem().Kind() { case reflect.Struct: v = v.Elem().FieldByName(key) + + case reflect.Slice: + // index is a number and get v from slice with index + index, err := strconv.Atoi(key) + if err != nil { + return newInvalidPathError(keyWithDots) + } + + if index >= v.Elem().Len() { + return newInvalidPathError(keyWithDots) + } + + v = v.Elem().Index(index) default: return newUnsupportedTypePathError(keyWithDots, v.Type()) }