示例#1
0
文件: gotmpl.go 项目: euank/gotmpl
func main() {
	env := flag.Bool("env", true, "Pull variables from the environment")
	inplace := flag.Bool("inplace", false, "Replace variables in the given file inplace")
	flag.Parse()
	remainingArgs := flag.Args()

	var tmplReader io.Reader
	var outWriter io.WriteCloser = os.Stdout
	defer outWriter.Close()

	if shouldReadStdin() {
		if *inplace {
			log.Fatal("Cannot do inplace replacement of stdin")
		}

		tmplReader = os.Stdin
	} else {
		if len(remainingArgs) == 0 {
			log.Fatal("Must provide an argument of a file to template")
		}
		fileName := remainingArgs[len(remainingArgs)-1]
		lastFile, err := os.Open(fileName)
		if err != nil {
			log.Fatalf("Could not open given file (%v) for templating: %v", fileName, err)
		}
		tmplReader = lastFile
		if *inplace {
			outWriter = &bufferedFileWriter{file: fileName, Buffer: bytes.NewBuffer([]byte{})}
		}
	}

	resolvers := chainResolver{}

	if *env {
		resolvers = append(resolvers, envLookup{})
	}

	vars := make(map[string]interface{})
	for _, arg := range remainingArgs {
		avar := make(map[string]interface{})
		f, err := os.Open(arg)
		if err != nil {
			log.Fatal("Unable to open file: " + arg)
		}
		data, err := ioutil.ReadAll(f)
		if err != nil {
			log.Fatal("Unable to read file: " + arg)
		}

		err = json.Unmarshal(data, &avar)
		if err != nil {
			log.Fatalf("Invalid json file %v: %v", arg, err)
		}

		for k, v := range avar {
			vars[k] = v
		}
	}

	strVars := make(gotmpl.MapLookup)
	for k, v := range vars {
		if v == nil {
			strVars[k] = ""
		} else {
			strVars[k] = fmt.Sprintf("%v", v)
		}
	}

	resolvers = append(resolvers, strVars)

	if err := gotmpl.Template(tmplReader, outWriter, resolvers); err != nil {
		log.Fatal(err)
	}
}
示例#2
0
func ExampleTemplate() {
	r := strings.NewReader(`Hello ${name}`)
	gotmpl.Template(r, os.Stdout, gotmpl.MapLookup(map[string]string{"name": "uhh, Jim"}))
	// Output: Hello uhh, Jim
}