From 2afba6b6a4beef346f7cb901535409b3ed9c9b71 Mon Sep 17 00:00:00 2001 From: Erik Unger Date: Thu, 16 May 2024 17:44:46 +0200 Subject: [PATCH] added MemFile.WriteJSON and WriteXML --- file_test.go | 2 +- memfile.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/file_test.go b/file_test.go index 47eae50..e346f10 100644 --- a/file_test.go +++ b/file_test.go @@ -228,5 +228,5 @@ func TestFile_ListDirInfoRecursiveContext(t *testing.T) { func TestFile_String(t *testing.T) { path := filepath.Join("dir", "file.ext") - require.Equal(t, "local file system: "+path, File(path).String()) + require.Equal(t, path+" (local file system)", File(path).String()) } diff --git a/memfile.go b/memfile.go index 2d9fe98..5bf62fd 100644 --- a/memfile.go +++ b/memfile.go @@ -251,6 +251,22 @@ func (f MemFile) ReadJSON(ctx context.Context, output any) error { return json.Unmarshal(f.FileData, output) } +// WriteJSON mashalles input to JSON and writes it as the file. +// Any indent arguments will be concanated and used as JSON line indentation. +func (f *MemFile) WriteJSON(ctx context.Context, input any, indent ...string) (err error) { + var data []byte + if len(indent) == 0 { + data, err = json.Marshal(input) + } else { + data, err = json.MarshalIndent(input, "", strings.Join(indent, "")) + } + if err != nil { + return err + } + f.FileData = data + return nil +} + // ReadXML reads and unmarshalles the XML content of the file to output. func (f MemFile) ReadXML(ctx context.Context, output any) error { if ctx.Err() != nil { @@ -259,6 +275,22 @@ func (f MemFile) ReadXML(ctx context.Context, output any) error { return xml.Unmarshal(f.FileData, output) } +// WriteXML mashalles input to XML and writes it as the file. +// Any indent arguments will be concanated and used as XML line indentation. +func (f *MemFile) WriteXML(ctx context.Context, input any, indent ...string) (err error) { + var data []byte + if len(indent) == 0 { + data, err = xml.Marshal(input) + } else { + data, err = xml.MarshalIndent(input, "", strings.Join(indent, "")) + } + if err != nil { + return err + } + f.FileData = append([]byte(xml.Header), data...) + return nil +} + // // MarshalJSON implements the json.Marshaler interface // func (f MemFile) MarshalJSON() ([]byte, error) { // encodedData := base64.RawURLEncoding.EncodeToString(f.FileData)