format.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package format
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. // OutputFormat represents the format for non-interactive mode output
  7. type OutputFormat string
  8. const (
  9. // TextFormat is plain text output (default)
  10. TextFormat OutputFormat = "text"
  11. // JSONFormat is output wrapped in a JSON object
  12. JSONFormat OutputFormat = "json"
  13. )
  14. // IsValid checks if the output format is valid
  15. func (f OutputFormat) IsValid() bool {
  16. return f == TextFormat || f == JSONFormat
  17. }
  18. // String returns the string representation of the output format
  19. func (f OutputFormat) String() string {
  20. return string(f)
  21. }
  22. // FormatOutput formats the given content according to the specified format
  23. func FormatOutput(content string, format OutputFormat) (string, error) {
  24. switch format {
  25. case TextFormat:
  26. return content, nil
  27. case JSONFormat:
  28. jsonData := map[string]string{
  29. "response": content,
  30. }
  31. jsonBytes, err := json.MarshalIndent(jsonData, "", " ")
  32. if err != nil {
  33. return "", fmt.Errorf("failed to marshal JSON: %w", err)
  34. }
  35. return string(jsonBytes), nil
  36. default:
  37. return "", fmt.Errorf("unsupported output format: %s", format)
  38. }
  39. }