...
1 package utils
2
3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7
8 "sigs.k8s.io/yaml"
9 )
10
11
12 func ConvertFromByte(b int64) *Unit {
13 const unit = 1000
14
15 div, exp := int64(unit), 0
16
17 for n := b / unit; n >= unit; n /= unit {
18 div *= unit
19 exp++
20 }
21
22 unitLabel := fmt.Sprintf("%cB",
23 "kMGTPE"[exp])
24
25 converedUnit := Unit{
26 Label: unitLabel,
27 Value: fmt.Sprintf("%.1f", float64(b)/float64(div)),
28 }
29
30 return &converedUnit
31 }
32
33 func YAMLToJSON(yamlStr *string) ([]byte, error) {
34 if IsNullOrEmpty(yamlStr) {
35 return nil, nil
36 }
37 js, err := yaml.YAMLToJSON([]byte(*yamlStr))
38 if err != nil {
39 return nil, err
40 }
41
42 if IsValidJSONObject(js) {
43 return js, nil
44 }
45 return nil, errors.New("not valid JSON")
46 }
47
48 func JSONToYAML(jsonStr *string) ([]byte, error) {
49 if IsNullOrEmpty(jsonStr) {
50 return nil, nil
51 }
52
53 return yaml.JSONToYAML([]byte(*jsonStr))
54 }
55
56 func ConvertStructToBase64(s interface{}) (string, error) {
57 structBytes, err := json.Marshal(s)
58 if err != nil {
59 return "", err
60 }
61 return ToBase64(structBytes), nil
62 }
63
View as plain text