Skip to content

Commit

Permalink
✨ feat(json,reflect): reflect add new util func for handle map data
Browse files Browse the repository at this point in the history
jsonutil:
- WritePretty

reflects:
- EachMap
- EachStrAnyMap
  • Loading branch information
inhere committed Mar 26, 2023
1 parent a3f173c commit 9e8a660
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
9 changes: 9 additions & 0 deletions jsonutil/jsonutil.go
Expand Up @@ -20,6 +20,15 @@ func WriteFile(filePath string, data any) error {
return os.WriteFile(filePath, jsonBytes, 0664)
}

// WritePretty write pretty data to JSON file
func WritePretty(filePath string, data any) error {
bs, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
return os.WriteFile(filePath, bs, 0664)
}

// ReadFile Read JSON file data
func ReadFile(filePath string, v any) error {
file, err := os.Open(filePath)
Expand Down
6 changes: 6 additions & 0 deletions jsonutil/jsonutil_test.go
Expand Up @@ -95,6 +95,12 @@ func TestWriteReadFile(t *testing.T) {
err := jsonutil.WriteFile("testdata/test.json", &user)
assert.NoErr(t, err)

err = jsonutil.WritePretty("testdata/test2.json", &user)
assert.NoErr(t, err)

// err = jsonutil.WritePretty("/path/to/not-exist.json", &user)
// assert.Err(t, err)

err = jsonutil.ReadFile("testdata/test.json", &user)
assert.NoErr(t, err)

Expand Down
21 changes: 21 additions & 0 deletions reflects/util.go
Expand Up @@ -82,6 +82,27 @@ func SetValue(rv reflect.Value, val any) error {
return err
}

// EachMap process any map data
func EachMap(mp reflect.Value, fn func(key, val reflect.Value)) {
if fn == nil {
return
}
if mp.Kind() != reflect.Map {
panic("only allow map value data")
}

for _, key := range mp.MapKeys() {
fn(key, mp.MapIndex(key))
}
}

// EachStrAnyMap process any map data as string key and any value
func EachStrAnyMap(mp reflect.Value, fn func(key string, val any)) {
EachMap(mp, func(key, val reflect.Value) {
fn(String(key), val.Interface())
})
}

// FlatFunc custom collect handle func
type FlatFunc func(path string, val reflect.Value)

Expand Down

0 comments on commit 9e8a660

Please sign in to comment.