/
output.go
69 lines (58 loc) · 1.38 KB
/
output.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package config
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclwrite"
)
//WriteFile returns outcome file and error just in case
func WriteFile(filename, format string, root *Root) (string, error) {
extension := filepath.Ext(filename)
if len(extension) > 0 {
extension = extension[1:]
filename = strings.TrimSuffix(filename, extension)
}
filename = fmt.Sprintf("%sconsul", filename)
// if format is not json/hcl use the same of the extension
if format != "json" && format != "hcl" {
format = extension
}
filename = fmt.Sprintf("%s.%s", filename, format)
f, err := os.Create(filename)
if err != nil {
return "", err
}
defer f.Close()
return filename, Write(f, format, root)
}
//Write info to do
func Write(w io.Writer, extension string, root *Root) error {
switch extension {
case "hcl":
return WriteHCL(w, root)
case "json":
return WriteJSON(w, root)
default:
return ErrorExtension
}
}
//WriteHCL the config in that language
func WriteHCL(w io.Writer, root *Root) error {
f := hclwrite.NewEmptyFile()
gohcl.EncodeIntoBody(root, f.Body())
_, err := f.WriteTo(w)
return err
}
//WriteJSON config in json
func WriteJSON(w io.Writer, root *Root) error {
payload, err := json.MarshalIndent(root, "", " ")
if err != nil {
return err
}
_, err = w.Write(payload)
return err
}