format.go 726 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package genopenapi
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "gopkg.in/yaml.v3"
  7. )
  8. type Format string
  9. const (
  10. FormatJSON Format = "json"
  11. FormatYAML Format = "yaml"
  12. )
  13. type ContentEncoder interface {
  14. Encode(v interface{}) (err error)
  15. }
  16. func (f Format) Validate() error {
  17. switch f {
  18. case FormatJSON, FormatYAML:
  19. return nil
  20. default:
  21. return errors.New("unknown format: " + string(f))
  22. }
  23. }
  24. func (f Format) NewEncoder(w io.Writer) (ContentEncoder, error) {
  25. switch f {
  26. case FormatYAML:
  27. enc := yaml.NewEncoder(w)
  28. enc.SetIndent(2)
  29. return enc, nil
  30. case FormatJSON:
  31. enc := json.NewEncoder(w)
  32. enc.SetIndent("", " ")
  33. return enc, nil
  34. default:
  35. return nil, errors.New("unknown format: " + string(f))
  36. }
  37. }