emissary/internal/format/registry.go

47 lines
830 B
Go

package format
import (
"io"
"github.com/pkg/errors"
)
type Format string
type Registry map[Format]Writer
var defaultRegistry = Registry{}
var ErrUnknownFormat = errors.New("unknown format")
func Write(format Format, writer io.Writer, hints Hints, data ...any) error {
formatWriter, exists := defaultRegistry[format]
if !exists {
return errors.WithStack(ErrUnknownFormat)
}
if hints.OutputMode == "" {
hints.OutputMode = OutputModeCompact
}
if err := formatWriter.Write(writer, hints, data...); err != nil {
return errors.WithStack(err)
}
return nil
}
func Available() []Format {
formats := make([]Format, 0, len(defaultRegistry))
for f := range defaultRegistry {
formats = append(formats, f)
}
return formats
}
func Register(format Format, writer Writer) {
defaultRegistry[format] = writer
}