2016-07-30 10:20:43 +00:00
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"text/template"
|
2017-02-15 23:14:47 +00:00
|
|
|
|
|
|
|
"github.com/ugorji/go/codec"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
jsonHandlePretty = &codec.JsonHandle{
|
|
|
|
HTMLCharsAsIs: true,
|
|
|
|
Indent: 4,
|
|
|
|
}
|
2016-07-30 10:20:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//DataFormatter is a transformer of the data.
|
|
|
|
type DataFormatter interface {
|
|
|
|
// TransformData should return transformed string data.
|
|
|
|
TransformData(interface{}) (string, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DataFormat returns the data formatter specified format.
|
|
|
|
func DataFormat(format, tmpl string) (DataFormatter, error) {
|
|
|
|
switch format {
|
|
|
|
case "json":
|
2016-08-04 10:19:31 +00:00
|
|
|
if len(tmpl) > 0 {
|
|
|
|
return nil, fmt.Errorf("json format does not support template option.")
|
|
|
|
}
|
2016-07-30 10:20:43 +00:00
|
|
|
return &JSONFormat{}, nil
|
|
|
|
case "template":
|
|
|
|
return &TemplateFormat{tmpl}, nil
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("Unsupported format is specified.")
|
|
|
|
}
|
|
|
|
|
|
|
|
type JSONFormat struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
// TransformData returns JSON format string data.
|
|
|
|
func (p *JSONFormat) TransformData(data interface{}) (string, error) {
|
2017-02-15 23:14:47 +00:00
|
|
|
var buf bytes.Buffer
|
|
|
|
enc := codec.NewEncoder(&buf, jsonHandlePretty)
|
|
|
|
err := enc.Encode(data)
|
2016-07-30 10:20:43 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2017-02-15 23:14:47 +00:00
|
|
|
return buf.String(), nil
|
2016-07-30 10:20:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type TemplateFormat struct {
|
|
|
|
tmpl string
|
|
|
|
}
|
|
|
|
|
|
|
|
// TransformData returns template format string data.
|
|
|
|
func (p *TemplateFormat) TransformData(data interface{}) (string, error) {
|
|
|
|
var out io.Writer = new(bytes.Buffer)
|
|
|
|
if len(p.tmpl) == 0 {
|
|
|
|
return "", fmt.Errorf("template needs to be specified the golang templates.")
|
|
|
|
}
|
|
|
|
|
2016-08-04 09:42:13 +00:00
|
|
|
t, err := template.New("format").Parse(p.tmpl)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = t.Execute(out, data)
|
2016-07-30 10:20:43 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return fmt.Sprint(out), nil
|
|
|
|
}
|