imap/export/json_exporter.go

36 lines
1.1 KiB
Go
Raw Permalink Normal View History

// Copyright (c) 2025 H0llyW00dzZ All rights reserved.
//
// By accessing or using this software, you agree to be bound by the terms
// of the License Agreement, which you can find at LICENSE files.
package export
import (
"encoding/json"
"fmt"
"io"
)
// JSONEncoderFunc defines a function type for custom JSON encoding
type JSONEncoderFunc func(v any, writer io.Writer) error
// JSONExporter implements the Exporter interface for JSON with a custom encoder
type JSONExporter struct {
Encoder JSONEncoderFunc
}
// Export writes messages to the writer as a JSON array using the custom JSON encoder
func (e *JSONExporter) Export(messages []map[string]any, writer io.Writer) error {
// Use the encoder to write the entire slice as a JSON array
if err := e.Encoder(messages, writer); err != nil {
return fmt.Errorf("failed to encode messages to JSON: %v", err)
}
return nil
}
// DefaultJSONEncoder is the default JSON encoding function using the standard library
func DefaultJSONEncoder(v any, writer io.Writer) error {
encoder := json.NewEncoder(writer)
return encoder.Encode(v)
}