-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
66 lines (54 loc) · 1.42 KB
/
json.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
package formats
import (
"encoding/json"
"github.com/dazfuller/azcosts/internal/model"
"os"
"time"
)
type report struct {
Generated time.Time `json:"generated"`
ResourceGroupCount int `json:"resourceGroupCount"`
TotalCost float64 `json:"totalCost"`
ResourceGroups []model.ResourceGroupSummary `json:"resourceGroups"`
}
type JsonFormatter struct {
useStdOut bool
outputPath string
}
func MakeJsonFormatter(useStdOut bool, outputPath string) (JsonFormatter, error) {
if err := validateOptions(useStdOut, outputPath); err != nil {
return JsonFormatter{}, err
}
return JsonFormatter{useStdOut: useStdOut, outputPath: outputPath}, nil
}
func (jf JsonFormatter) Generate(costs []model.ResourceGroupSummary) error {
totalCost := float64(0)
for i := range costs {
totalCost += costs[i].TotalCost
}
report := report{
Generated: time.Now().UTC(),
ResourceGroupCount: len(costs),
TotalCost: totalCost,
ResourceGroups: costs,
}
if jf.useStdOut {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(report); err != nil {
return err
}
return nil
}
file, err := os.Create(jf.outputPath)
if err != nil {
return err
}
defer file.Close()
enc := json.NewEncoder(file)
enc.SetIndent("", " ")
if err := enc.Encode(report); err != nil {
return err
}
return nil
}