如何使用Golang模板missingkey选项?

I would expect

t, err := template.New("t1").Option("missingkey=error").Parse("{{index . \"/foo/bar\"}}")        
err = t.Execute(os.Stdout, d)

to return an error if the map 'd' doesn't have a key '/foo/bar', but everything is just fine. Am I missing something?

Here's the go playground: http://play.golang.org/p/Oqg1Dy4h1k

The missingkey option does not work with index. You will only get the desired result when you access the map using .<field-name>:

t, err := template.New("t1").Option("missingkey=error").Parse(`{{.foo}}`)
err = t.Execute(os.Stdout, d)

You can get around this by defining your own index function that returns an error when a key is missing:

package main

import (
    "errors"
    "fmt"
    "os"
    "text/template"
)

func lookup(m map[string]interface{}, key string) (interface{}, error) {
    val, ok := m[key]
    if !ok {
        return nil, errors.New("missing key " + key)
    }
    return val, nil
}

func main() {
    d := map[string]interface{}{
        "/foo/bar": 34,
    }
    fns := template.FuncMap{
        "lookup": lookup,
    }
    t, err := template.New("t1").Funcs(fns).Parse(`{{ lookup . "/foo/baz" }}`)
    if err != nil {
        fmt.Println("ERROR 1")
    }
    err = t.Execute(os.Stdout, d)
    if err != nil {
        fmt.Println("ERROR 2")
    }
}

https://play.golang.org/p/L12lFnJig_