1
0
mirror of https://github.com/golang/go synced 2024-11-23 20:00:04 -07:00

text/template: handle option missingkey=error consistently

The existing implementation of text/template handles the option
"missingkey=error" in an inconsitent manner:  If the provided data is
a nil-interface, no error is returned (despite the fact that no key
can be found in it).

This patch makes text/template return an error if "missingkey=error"
is set and the provided data is a not a valid reflect.Value.

Fixes #15356

Change-Id: Ia0a83da48652ecfaf31f18bdbd78cb21dbca1164
Reviewed-on: https://go-review.googlesource.com/31638
Reviewed-by: Rob Pike <r@golang.org>
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Özgür Kesim 2016-10-21 13:14:57 +02:00 committed by Rob Pike
parent 348275cda6
commit 277bcbbdcd
2 changed files with 9 additions and 0 deletions

View File

@ -541,6 +541,9 @@ func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd
// value of the pipeline, if any. // value of the pipeline, if any.
func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value { func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
if !receiver.IsValid() { if !receiver.IsValid() {
if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
s.errorf("nil data; no entry for key %q", fieldName)
}
return zero return zero
} }
typ := receiver.Type() typ := receiver.Type()

View File

@ -1142,6 +1142,12 @@ func TestMissingMapKey(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("expected error; got none") t.Errorf("expected error; got none")
} }
// same Option, but now a nil interface: ask for an error
err = tmpl.Execute(&b, nil)
t.Log(err)
if err == nil {
t.Errorf("expected error for nil-interface; got none")
}
} }
// Test that the error message for multiline unterminated string // Test that the error message for multiline unterminated string