From 77af24d7cc3eaec952a011fed9c7cff6e71870f5 Mon Sep 17 00:00:00 2001 From: Volker Schukai <volker.schukai@schukai.com> Date: Wed, 13 Sep 2023 21:45:09 +0200 Subject: [PATCH] feat: set support slieces #8 --- issue_7_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ set.go | 13 +++++++++++++ 2 files changed, 58 insertions(+) diff --git a/issue_7_test.go b/issue_7_test.go index 7eb118b..4b6bf62 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 1c1a387..8004d05 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()) } -- GitLab