Skip to content

Instantly share code, notes, and snippets.

@tenfyzhong
Last active May 10, 2019 01:57
Show Gist options
  • Save tenfyzhong/9e41cc23cf982f33ab13dc8223acd85e to your computer and use it in GitHub Desktop.
Save tenfyzhong/9e41cc23cf982f33ab13dc8223acd85e to your computer and use it in GitHub Desktop.
用环境变量渲染template
package main
import (
"flag"
"fmt"
"os"
"strings"
"text/template"
)
var (
tempfile = ""
)
func init() {
flag.StringVar(&tempfile, "t", "", "template file")
}
func main() {
flag.Parse()
t, err := template.ParseFiles(tempfile)
if err != nil {
fmt.Fprintf(os.Stderr, "parse tempfile failed, %v\n", err)
os.Exit(1)
}
data := make(map[string]string)
for _, s := range os.Environ() {
items := strings.SplitN(s, "=", 2)
if len(items) != 2 {
continue
}
name := items[0]
value := items[1]
data[name] = value
}
err = t.Execute(os.Stdout, data)
if err != nil {
fmt.Fprintf(os.Stderr, "execute template %v", err)
os.Exit(3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment