goweb/cli/format/json/writer.go

39 lines
637 B
Go
Raw Normal View History

2023-12-15 20:01:37 +01:00
package json
import (
"encoding/json"
"io"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/cli/format"
)
const Format format.Format = "json"
func init() {
format.Register(Format, NewWriter())
}
type Writer struct{}
// Format implements format.Writer.
func (*Writer) Write(writer io.Writer, hints format.Hints, data ...any) error {
encoder := json.NewEncoder(writer)
if hints.OutputMode == format.OutputModeWide {
encoder.SetIndent("", " ")
}
if err := encoder.Encode(data); err != nil {
return errors.WithStack(err)
}
return nil
}
func NewWriter() *Writer {
return &Writer{}
}
var _ format.Writer = &Writer{}