forked from argoproj/argo-workflows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
74 lines (65 loc) · 2.09 KB
/
config.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
70
71
72
73
74
package cli
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/ghodss/yaml"
)
// unmarshalObject tries to convert a YAML or JSON byte array into the provided type.
func unmarshalObject(data []byte, obj interface{}) error {
// first, try unmarshaling as JSON
// Based on technique from Kubectl, which supports both YAML and JSON:
// https://mlafeldt.github.io/blog/teaching-go-programs-to-love-json-and-yaml/
// http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/
// Short version: JSON unmarshaling won't zero out null fields; YAML unmarshaling will.
// This may have unintended effects or hard-to-catch issues when populating our application object.
jsonData, err := yaml.YAMLToJSON(data)
if err != nil {
return err
}
err = json.Unmarshal(jsonData, &obj)
if err != nil {
return err
}
return err
}
// MarshalLocalYAMLFile writes JSON or YAML to a file on disk.
// The caller is responsible for checking error return values.
func MarshalLocalYAMLFile(path string, obj interface{}) error {
yamlData, err := yaml.Marshal(obj)
if err == nil {
err = ioutil.WriteFile(path, yamlData, 0600)
}
return err
}
// UnmarshalLocalFile retrieves JSON or YAML from a file on disk.
// The caller is responsible for checking error return values.
func UnmarshalLocalFile(path string, obj interface{}) error {
data, err := ioutil.ReadFile(path)
if err == nil {
err = unmarshalObject(data, obj)
}
return err
}
// UnmarshalRemoteFile retrieves JSON or YAML through a GET request.
// The caller is responsible for checking error return values.
func UnmarshalRemoteFile(url string, obj interface{}) error {
data, err := readRemoteFile(url)
if err == nil {
err = unmarshalObject(data, obj)
}
return err
}
// ReadRemoteFile issues a GET request to retrieve the contents of the specified URL as a byte array.
// The caller is responsible for checking error return values.
func readRemoteFile(url string) ([]byte, error) {
var data []byte
resp, err := http.Get(url)
if err == nil {
defer func() {
_ = resp.Body.Close()
}()
data, err = ioutil.ReadAll(resp.Body)
}
return data, err
}