mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-24 17:28:31 +02:00
fix(serialization): treat empty LoadFileIfExist paths like missing files
When a path exists but reads as empty or whitespace-only, return nil without touching dst, matching the no-file case. This avoids unmarshaler errors on blank files and matches the updated doc comment.
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
package serialization
|
package serialization
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -727,7 +728,7 @@ func SaveFile[T any](path string, src *T, perm os.FileMode, marshaler marshalFun
|
|||||||
|
|
||||||
// LoadFileIfExist reads a file and unmarshals its contents to a value.
|
// LoadFileIfExist reads a file and unmarshals its contents to a value.
|
||||||
// - The unmarshaler function converts the bytes to a value.
|
// - The unmarshaler function converts the bytes to a value.
|
||||||
// - If the file does not exist, nil is returned and dst remains unchanged.
|
// - If the file does not exist or is empty, nil is returned and dst remains unchanged.
|
||||||
func LoadFileIfExist[T any](path string, dst *T, unmarshaler unmarshalFunc) error {
|
func LoadFileIfExist[T any](path string, dst *T, unmarshaler unmarshalFunc) error {
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -736,5 +737,8 @@ func LoadFileIfExist[T any](path string, dst *T, unmarshaler unmarshalFunc) erro
|
|||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if len(bytes.TrimSpace(data)) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
return unmarshaler(data, dst)
|
return unmarshaler(data, dst)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user