2020-08-13 15:43:55 +02:00
|
|
|
package envtemplate
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2022-10-18 09:28:39 +02:00
|
|
|
"fmt"
|
2020-08-13 15:43:55 +02:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/valyala/fasttemplate"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Replace replaces `%{ENV_VAR}` placeholders in b with the corresponding ENV_VAR values.
|
2022-10-18 09:28:39 +02:00
|
|
|
//
|
|
|
|
// Error is returned if ENV_VAR isn't set for some `%{ENV_VAR}` placeholder.
|
|
|
|
func Replace(b []byte) ([]byte, error) {
|
2020-08-13 15:43:55 +02:00
|
|
|
if !bytes.Contains(b, []byte("%{")) {
|
|
|
|
// Fast path - nothing to replace.
|
2022-10-18 09:28:39 +02:00
|
|
|
return b, nil
|
2020-08-13 15:43:55 +02:00
|
|
|
}
|
2022-10-18 09:28:39 +02:00
|
|
|
s, err := fasttemplate.ExecuteFuncStringWithErr(string(b), "%{", "}", func(w io.Writer, tag string) (int, error) {
|
|
|
|
v, ok := os.LookupEnv(tag)
|
|
|
|
if !ok {
|
|
|
|
return 0, fmt.Errorf("missing %q environment variable", tag)
|
2020-08-13 15:43:55 +02:00
|
|
|
}
|
|
|
|
return w.Write([]byte(v))
|
|
|
|
})
|
2022-10-18 09:28:39 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return []byte(s), nil
|
2020-08-13 15:43:55 +02:00
|
|
|
}
|