mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-10 18:56:55 +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
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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.
|
||||
// - 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 {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -736,5 +737,8 @@ func LoadFileIfExist[T any](path string, dst *T, unmarshaler unmarshalFunc) erro
|
||||
}
|
||||
return err
|
||||
}
|
||||
if len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil
|
||||
}
|
||||
return unmarshaler(data, dst)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user