forked from golang-migrate/migrate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.go
47 lines (39 loc) · 841 Bytes
/
template.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
package migrate
import (
"fmt"
"io"
"os"
"strings"
"text/template"
)
var envMapCache map[string]string
func envMap() map[string]string {
if envMapCache != nil {
return envMapCache
}
envMapCache = make(map[string]string)
for _, kvp := range os.Environ() {
kvParts := strings.SplitN(kvp, "=", 2)
envMapCache[kvParts[0]] = kvParts[1]
}
return envMapCache
}
func applyEnvironmentTemplate(body io.ReadCloser) (io.ReadCloser, error) {
bodyBytes, err := io.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("reading body: %w", err)
}
defer func() {
_ = body.Close()
}()
tmpl, err := template.New("migration").Parse(string(bodyBytes))
if err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
r, w := io.Pipe()
go func() {
_ = tmpl.Execute(w, envMap())
_ = w.Close()
}()
return r, nil
}