refactor: focus around Render/Compact/Pretty/NewWith functions

This is yet another drastic refactor of public API and concepts.
Hopefully the last one, as I'm now fairly happy with things.
This commit is contained in:
2024-03-25 01:40:31 +00:00
parent de3a9e55a8
commit e2e2754970
18 changed files with 1462 additions and 387 deletions

52
json.go
View File

@@ -6,36 +6,49 @@ import (
"io"
)
// JSON is a renderer that marshals values to JSON.
type JSON struct {
// Pretty specifies whether the output should be pretty-printed. If true,
// the output will be indented and newlines will be added.
Pretty bool
// JSONDefualtIndent is the default indentation string used by JSON instances
// when pretty rendering if no Indent value is set on the JSON instance itself.
var JSONDefualtIndent = " "
// Prefix is the prefix added to each level of indentation when Pretty is
// true.
// JSON is a Handler that marshals values to JSON.
type JSON struct {
// Prefix is the prefix added to each level of indentation when pretty
// rendering.
Prefix string
// Indent is the string added to each level of indentation when Pretty is
// true. If empty, two spaces will be used instead.
// Indent is the string added to each level of indentation when pretty
// rendering. If empty, two spaces will be used instead.
Indent string
}
var _ FormatRenderer = (*JSON)(nil)
var (
_ Handler = (*JSON)(nil)
_ PrettyHandler = (*JSON)(nil)
_ FormatsHandler = (*JSON)(nil)
)
// Render marshals the given value to JSON.
func (jr *JSON) Render(w io.Writer, v any) error {
enc := json.NewEncoder(w)
if jr.Pretty {
prefix := jr.Prefix
indent := jr.Indent
if indent == "" {
indent = " "
}
enc.SetIndent(prefix, indent)
err := json.NewEncoder(w).Encode(v)
if err != nil {
return fmt.Errorf("%w: %w", ErrFailed, err)
}
return nil
}
// RenderPretty marshals the given value to JSON with line breaks and
// indentation.
func (jr *JSON) RenderPretty(w io.Writer, v any) error {
prefix := jr.Prefix
indent := jr.Indent
if indent == "" {
indent = JSONDefualtIndent
}
enc := json.NewEncoder(w)
enc.SetIndent(prefix, indent)
err := enc.Encode(v)
if err != nil {
return fmt.Errorf("%w: %w", ErrFailed, err)
@@ -44,6 +57,7 @@ func (jr *JSON) Render(w io.Writer, v any) error {
return nil
}
// Formats returns a list of format strings that this Handler supports.
func (jr *JSON) Formats() []string {
return []string{"json"}
}