Get number of bytes written by template.Execute

204 views
Skip to first unread message

Matt Sherman

unread,
Oct 18, 2014, 11:02:09 PM10/18/14
to golan...@googlegroups.com
Is there a cleaner way of getting the number of bytes written by text/template.Execute, other than writing to a temporary buffer? Here's my current code, given an already-parsed template tmpl and a destination io.Writer w.

var b bytes.Buffer
tmpl.Execute(&b, data)
n, err = w.Write(b.Bytes())

... where n is the number I am looking for. The above is straightforward enough, but it's two writes instead of one. It also takes more memory, I assume. I'd prefer to execute the template against w directly. (Is there a role for bufio, perhaps?) Thanks.

David Symonds

unread,
Oct 19, 2014, 12:06:47 AM10/19/14
to Matt Sherman, golang-nuts
Implement a trivial counting writer.

type counter struct {
n int
w io.Writer
}

func (c *counter) Write(p []byte) (n int, err error) {
n, err = c.w.Write(p)
c.n += n
return
}

That has a fixed constant memory overhead, and very little per-write overhead.

Lars Seipel

unread,
Oct 19, 2014, 12:09:28 AM10/19/14
to Matt Sherman, golan...@googlegroups.com
On Sat, Oct 18, 2014 at 08:02:09PM -0700, Matt Sherman wrote:
> Is there a cleaner way of getting the number of bytes written by
> text/template.Execute, other than writing to a temporary buffer?

Implement a writer that wraps your destination writer and records the
number of bytes as they are written. No need to buffer the whole output.

See http://play.golang.org/p/a7gCZq7Hio for an example.

Lars

Dave Cheney

unread,
Oct 20, 2014, 4:50:40 AM10/20/14
to golan...@googlegroups.com


On Sunday, 19 October 2014 14:02:09 UTC+11, Matt Sherman wrote:
Is there a cleaner way of getting the number of bytes written by text/template.Execute, other than writing to a temporary buffer? Here's my current code, given an already-parsed template tmpl and a destination io.Writer w.

var b bytes.Buffer
tmpl.Execute(&b, data)
n, err = w.Write(b.Bytes())


io.Copy(w, b)

possibly to avoid the second Write, but the idea of a counting writer is probably better.
Reply all
Reply to author
Forward
0 new messages