common.go 884 字节
Newer Older
LinuxSuRen's avatar
LinuxSuRen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
package cmd

import (
	"encoding/json"
	"fmt"

	"gopkg.in/yaml.v2"
)

type OutputOption struct {
	Format string
}

14 15 16 17
type FormatOutput interface {
	Output(obj interface{}, format string) (data []byte, err error)
}

LinuxSuRen's avatar
LinuxSuRen 已提交
18
const (
19 20 21
	JsonOutputFormat  string = "json"
	YAMLOutputFormat  string = "yaml"
	TableOutputFormat string = "table"
LinuxSuRen's avatar
LinuxSuRen 已提交
22 23
)

24 25 26 27 28 29 30 31 32 33 34
func (o *OutputOption) Output(obj interface{}) (data []byte, err error) {
	switch o.Format {
	case JsonOutputFormat:
		return json.MarshalIndent(obj, "", "  ")
	case YAMLOutputFormat:
		return yaml.Marshal(obj)
	}

	return nil, fmt.Errorf("not support format %s", o.Format)
}

LinuxSuRen's avatar
LinuxSuRen 已提交
35 36 37 38 39 40 41 42 43
func Format(obj interface{}, format string) (data []byte, err error) {
	if format == JsonOutputFormat {
		return json.MarshalIndent(obj, "", "  ")
	} else if format == YAMLOutputFormat {
		return yaml.Marshal(obj)
	}

	return nil, fmt.Errorf("not support format %s", format)
}