Skip to content

Commit

Permalink
added MemFile.WriteJSON and WriteXML
Browse files Browse the repository at this point in the history
  • Loading branch information
ungerik committed May 16, 2024
1 parent a606985 commit 2afba6b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
32 changes: 32 additions & 0 deletions memfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down

0 comments on commit 2afba6b

Please sign in to comment.