Skip to content

Commit cebfad9

Browse files
committed
Add helper method to config.Secret to load a file
LoadFromFile is a very small helper to avoid repeating this code over and over again. This is related to prometheus/prometheus#8551 Signed-off-by: Marcelo E. Magallon <[email protected]>
1 parent 8d1c9f8 commit cebfad9

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

config/config.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ package config
1818

1919
import (
2020
"encoding/json"
21+
"fmt"
22+
"io/ioutil"
2123
"path/filepath"
2224
)
2325

@@ -48,6 +50,15 @@ func (s Secret) MarshalJSON() ([]byte, error) {
4850
return json.Marshal(secretToken)
4951
}
5052

53+
func (s *Secret) LoadFromFile(filename string) error {
54+
buf, err := ioutil.ReadFile(filename)
55+
if err != nil {
56+
return fmt.Errorf("cannot read %s: %w", filename, err)
57+
}
58+
*s = Secret(buf)
59+
return nil
60+
}
61+
5162
// DirectorySetter is a config type that contains file paths that may
5263
// be relative to the file containing the config.
5364
type DirectorySetter interface {

config/config_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ package config
1717

1818
import (
1919
"encoding/json"
20+
"io/ioutil"
21+
"os"
2022
"testing"
2123
)
2224

@@ -53,3 +55,55 @@ func TestJSONMarshalSecret(t *testing.T) {
5355
})
5456
}
5557
}
58+
59+
func TestSecretLoadFromFile(t *testing.T) {
60+
dn, err := ioutil.TempDir("", "test-secret-loadfromfile.")
61+
if err != nil {
62+
t.Fatalf("cannot create temporary directory: %s", err)
63+
}
64+
defer os.RemoveAll(dn)
65+
66+
fh, err := ioutil.TempFile(dn, "")
67+
if err != nil {
68+
t.Fatalf("cannot create temporary file: %s", err)
69+
}
70+
71+
fn := fh.Name()
72+
73+
secretData := "test"
74+
75+
n, err := fh.WriteString(secretData)
76+
if err != nil {
77+
t.Fatalf("cannot write to temporary file %s: %s", fn, err)
78+
}
79+
80+
if n != len(secretData) {
81+
t.Fatalf("short write writing to temporary file %s, expecting %d, got %d", fn, len(secretData), n)
82+
}
83+
84+
err = fh.Close()
85+
if err != nil {
86+
t.Fatalf("error closing temporary file %s after write: %s", fn, err)
87+
}
88+
89+
var s Secret
90+
err = s.LoadFromFile(fn)
91+
if err != nil {
92+
t.Fatalf("cannot read secret from temporary file %s: %s", fn, err)
93+
}
94+
95+
if string(s) != secretData {
96+
t.Fatalf("unexpected secret data, expected %q, actual %q", secretData, string(s))
97+
}
98+
99+
err = os.Remove(fn)
100+
if err != nil {
101+
t.Fatalf("cannot remove temporary file %s: %s", fn, err)
102+
}
103+
104+
// this should report an error now
105+
err = s.LoadFromFile(fn)
106+
if err == nil {
107+
t.Fatalf("expecting error reading non-existent temporary file %s, got nil", fn)
108+
}
109+
}

0 commit comments

Comments
 (0)