Combine FuncMap With Strict MissingKey

Register custom text/template FuncMap helpers and contrast missingkey=zero against missingkey=error so absent keys either default cleanly or fail.

GoConfig Management

Code

snippet
package main

import (
	"bytes"
	"fmt"
	"strings"
	"text/template"
)

func renderWithMode(mode, src string, data map[string]string) (string, error) {
	funcs := template.FuncMap{
		"orDefault": func(fallback, val string) string {
			if strings.TrimSpace(val) == "" {
				return fallback
			}
			return val
		},
		"upper": strings.ToUpper,
	}
	tpl, err := template.New("env").Funcs(funcs).Option("missingkey=" + mode).Parse(src)
	if err != nil {
		return "", err
	}
	var out bytes.Buffer
	if err := tpl.Execute(&out, data); err != nil {
		return "", err
	}
	return out.String(), nil
}

func main() {
	src := `service={{ upper .service }} region={{ orDefault "us-east" .region }}`
	cfg := map[string]string{"service": "billing"}

	// missingkey=zero passes "" to orDefault instead of "<no value>"
	zeroOut, zeroErr := renderWithMode("zero", src, cfg)
	fmt.Printf("zero mode:   %q err=%v\n", zeroOut, zeroErr)

	// missingkey=error rejects the missing key immediately
	errOut, strictErr := renderWithMode("error", src, cfg)
	fmt.Printf("strict mode: %q err=%v\n", errOut, strictErr)

	// When all keys exist, strict mode succeeds
	full := map[string]string{"service": "billing", "region": "eu-central"}
	okOut, okErr := renderWithMode("error", src, full)
	fmt.Printf("strict full: %q err=%v\n", okOut, okErr)
}

Walkthrough notes — Combine FuncMap With Strict MissingKey

Combine FuncMap With Strict MissingKey keeps everything in the functions renderWithMode and main.

Error handling is inline: 2 places test err != nil and branch immediately.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • There are no exceptions to catch — err return values must be checked at each call site.

Putting it to use

Entry signature: func renderWithMode(mode, src string, data map[string]string) (string, error)

Output lines are prefixed (zero mode:, strict mode:, strict full:), surfacing concrete execution results across sequential stdout rows.

main is the driver: it invokes renderWithMode before returning.

Core lines

if err != nil {
	return "", err
}
return out.String(), nil

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As returned `error` values — 2 sites in the snippet check `err` before using other results.
What does Combine FuncMap With Strict MissingKey print when run?
The script runs standalone; its 3 labeled outputs include `zero mode:`, `strict mode:`, `strict full:`.