-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
secret.go
50 lines (41 loc) · 1.33 KB
/
secret.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
package config
import (
"fmt"
"os"
"strings"
)
// Secret represents a secret value that can be a plain string or a file path.
// If the value starts with "file://", it is treated as a file path, and the secret value is read from the file.
// The "file://" syntax supports environment variables.
// For example, "file://$HOME/my_secret.txt" would read the secret from the "my_secret.txt" file in the user's home directory.
type Secret string
// String reassembles the Secret into a valid string.
//
//goland:noinspection GoMixedReceiverTypes
func (secret Secret) String() string {
return string(secret)
}
// MarshalText implements [encoding.TextMarshaler] interface for Secret
//
//goland:noinspection GoMixedReceiverTypes
func (secret Secret) MarshalText() ([]byte, error) {
return []byte(secret), nil
}
// UnmarshalText implements the [encoding.TextUnmarshaler] interface for Secret
//
//goland:noinspection GoMixedReceiverTypes
func (secret *Secret) UnmarshalText(text []byte) error {
stringText := string(text)
switch {
case strings.HasPrefix(stringText, "file://"):
filePath := os.ExpandEnv(strings.TrimPrefix(stringText, "file://"))
body, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("unable read secret %s: %w", filePath, err)
}
*secret = Secret(body)
default:
*secret = Secret(stringText)
}
return nil
}