golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.88k stars 17.52k forks source link

proposal: text/template/v2: return errors from HTMLEscape and JSEscape #29003

Open bcmills opened 5 years ago

bcmills commented 5 years ago

template.HTMLEscape and template.JSEscape each accept an io.Writer and write to it. However, they ignore errors from Write.

That's fine when the destination io.Writer is one that cannot fail (such as a *bytes.Buffer), but can mask real errors in general (see also https://github.com/golang/go/issues/20803#issuecomment-312318808).

It is possible for the caller to detect those errors by wrapping the io.Writer, but wrapping an io.Writer to capture an error that it already returns needlessly complicates the code.

These functions should return errors, and leave the decision about whether those errors are safe to ignore up to the caller.

Compatibility

This change would be call-site compatible (leaving the vast majority of callers unchanged), but would break programs that pass or assign template.HTMLEscape or template.JSEscape as a func(io.Writer, []byte). Such uses should be rare.

As an alternative, we could add variants of those functions that do return errors; however, separate variants would mask missing error checks from analysis tools. I believe it would be better to simply change the signature in a Go 2 cleanup.

bcmills commented 5 years ago

(CC @robpike @mvdan)

mvdan commented 5 years ago

Sounds good to me. I think for Go2 we should review the standard library, and consider fixing all functions and methods that take an io.Writer but don't return an error.

I wonder if we should do the same for other parameter types, like io.Reader.