github.com/mongey/nomad@v0.5.2/command/data_format.go (about) 1 package command 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "text/template" 9 ) 10 11 //DataFormatter is a transformer of the data. 12 type DataFormatter interface { 13 // TransformData should return transformed string data. 14 TransformData(interface{}) (string, error) 15 } 16 17 // DataFormat returns the data formatter specified format. 18 func DataFormat(format, tmpl string) (DataFormatter, error) { 19 switch format { 20 case "json": 21 if len(tmpl) > 0 { 22 return nil, fmt.Errorf("json format does not support template option.") 23 } 24 return &JSONFormat{}, nil 25 case "template": 26 return &TemplateFormat{tmpl}, nil 27 } 28 return nil, fmt.Errorf("Unsupported format is specified.") 29 } 30 31 type JSONFormat struct { 32 } 33 34 // TransformData returns JSON format string data. 35 func (p *JSONFormat) TransformData(data interface{}) (string, error) { 36 out, err := json.MarshalIndent(&data, "", " ") 37 if err != nil { 38 return "", err 39 } 40 41 return string(out), nil 42 } 43 44 type TemplateFormat struct { 45 tmpl string 46 } 47 48 // TransformData returns template format string data. 49 func (p *TemplateFormat) TransformData(data interface{}) (string, error) { 50 var out io.Writer = new(bytes.Buffer) 51 if len(p.tmpl) == 0 { 52 return "", fmt.Errorf("template needs to be specified the golang templates.") 53 } 54 55 t, err := template.New("format").Parse(p.tmpl) 56 if err != nil { 57 return "", err 58 } 59 60 err = t.Execute(out, data) 61 if err != nil { 62 return "", err 63 } 64 return fmt.Sprint(out), nil 65 }