Skip to content

Instantly share code, notes, and snippets.

@heaths
Last active November 16, 2022 18:05
Show Gist options
  • Save heaths/bf3ba7d0cbc60376b60773aa78eb1ef0 to your computer and use it in GitHub Desktop.
Save heaths/bf3ba7d0cbc60376b60773aa78eb1ef0 to your computer and use it in GitHub Desktop.
Prompt for input and cache during template execution
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"strings"
"text/template"
)
func main() {
cache := make(map[string]string)
for i := 1; i < len(os.Args); i++ {
tokens := strings.SplitN(os.Args[i], "=", 2)
if len(tokens) != 2 {
log.Fatal("parameters must be passed as name=value")
}
name, value := tokens[0], tokens[1]
cache[name] = value
}
funcs := template.FuncMap{
"param": func(name string, params ...string) (value string, err error) {
var ok bool
if value, ok = cache[name]; !ok {
defaultValue := ""
if len(params) > 0 {
defaultValue = params[0]
}
prompt := name
if len(params) > 1 {
prompt = fmt.Sprintf("%s (%s)", params[1], name)
}
reader := bufio.NewReader(os.Stdin)
fmt.Fprintf(os.Stderr, "\033[32m%s? \033[90m[%s]\033[0m: ", prompt, defaultValue)
value, err = reader.ReadString('\n')
if err != nil {
return
}
value = strings.TrimSpace(value)
if value == "" {
value = defaultValue
}
cache[name] = value
}
return
},
}
templ, err := template.New("").Funcs(funcs).Parse(`Hello, {{param "name" "world" "Who should I greet"}}! It's nice to meet you, {{param "name"}}.`)
if err != nil {
log.Fatalf("failed to parse template: %v", err)
}
buffer := &bytes.Buffer{}
err = templ.Execute(buffer, nil)
if err != nil {
log.Fatalf("failed to execute template: %v", err)
}
fmt.Println(buffer.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment