godev-null

Golang - Discard as WriteCloser


I needed to create an equivalent of ioutil.Discard that can satisfy a "WriteCloser" interface. With a bit of Googling I came up with

package main

import (
    "io"
    "io/ioutil"
    "strings"
    "fmt"
)

type discardCloser struct {
    io.Writer
}

func (discardCloser) Close() error {
    return nil
}

func main() {
    src := strings.NewReader("Hello world")
    dst := discardCloser{Writer: ioutil.Discard}
    count, err := io.Copy(dst, src)
    fmt.Println(count, err)
    err = dst.Close()
    fmt.Println(err)
}

Go playground link here

Is there a more idiomatic way of doing this?

Background: some standard library methods return a WriteCloser, such as net/smtp.Data. When implementing automated tests, it's nice to be able to exercise functions like this, while sending their output to Discard.


Solution

  • I took bereal's tip and looked at NopCloser. The approach works nicely, and is useful in test functions built around the libraries that require a WriteCloser.

    I renamed the type myWriteCloser as it can be used to promote "real" writers such as as &bytes.Buffer, as well as the special system discard writer.

    type myWriteCloser struct {
        io.Writer
    }
    
    func (myWriteCloser) Close() error {
        return nil
    }