github.com/SigNoz/golang-migrate/v4@v4.0.0-20231005133642-7493dbaf5f5b/template.go (about) 1 package migrate 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 "strings" 8 "text/template" 9 ) 10 11 var envMapCache map[string]string 12 13 func envMap() map[string]string { 14 if envMapCache != nil { 15 return envMapCache 16 } 17 envMapCache = make(map[string]string) 18 for _, kvp := range os.Environ() { 19 kvParts := strings.SplitN(kvp, "=", 2) 20 envMapCache[kvParts[0]] = kvParts[1] 21 } 22 return envMapCache 23 } 24 25 func applyEnvironmentTemplate(body io.ReadCloser) (io.ReadCloser, error) { 26 bodyBytes, err := io.ReadAll(body) 27 if err != nil { 28 return nil, fmt.Errorf("reading body: %w", err) 29 } 30 defer func() { 31 _ = body.Close() 32 }() 33 34 tmpl, err := template.New("migration").Parse(string(bodyBytes)) 35 if err != nil { 36 return nil, fmt.Errorf("parsing template: %w", err) 37 } 38 39 r, w := io.Pipe() 40 41 go func() { 42 _ = tmpl.Execute(w, envMap()) 43 _ = w.Close() 44 }() 45 46 return r, nil 47 }