Richard Bucker

The Sticky Wrapper class

Posted at — Feb 27, 2015

I was watching a live programming session with Andrew Gerrand and Brad Fitzpatrick where they hacked an http_2 client; when they demonstrated something called a stickyErrWriter. If you’ve ever written a block of code which calls a group of related functions with potential error return functions then you got gobs of  if err != nil after each call. Yuk!An instance is declared = bufio.NewWriter(stickyErrWriter{tconn, &cc.werr})This is the idiomatic way Go treats readers and writers; and similar packages.The stickyErrWriter structure overrides the Write method so that when the base function, in this case Flush(), when Flush() calls Write() it’s the sticky Write that is called which checks the current error state; and if there is no error then the actual Write() is called.func (sew stickyErrWriter) Write(p []byte) (n int, err error) {        if *sew.err != nil {                return 0, *sew.err        }        n, err = sew.w.Write(p)        *sew.err = err        return}This is a great example.Another idiomatic example is the NopCloser()."NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.“The NopCloser provides a Close() method that does nothing. It’s for io.Reader instances that do not provide their own Close() method but where a Close() is required.