29

Does anyone have a good or any explanation of Golang's NopCloser function?
I looked around but failed to find anything besides Golang's main doc's explanation of:

NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.

Any pointers or explanation would be appreciated. Thanks.

Ivan Aracki
  • 3,668
  • 8
  • 47
  • 63
G4143
  • 1,912
  • 4
  • 15
  • 19

3 Answers3

31

Whenever you need to return an io.ReadCloser, while making sure a Close() is available, you can use a NopCloser to build such a ReaderCloser.

You can see one example in this fork of gorest, in util.go

//Marshals the data in interface i into a byte slice, using the Marhaller/Unmarshaller specified in mime.
//The Marhaller/Unmarshaller must have been registered before using gorest.RegisterMarshaller
func InterfaceToBytes(i interface{}, mime string) (io.ReadCloser, error) {
    v := reflect.ValueOf(i)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    switch v.Kind() {
    case reflect.Bool:
        x := v.Bool()
        if x {
            return ioutil.NopCloser(bytes.NewBuffer([]byte("true"))), nil
        }
Community
  • 1
  • 1
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
13

It's used for functions that require io.ReadCloser but your current object (for example a bytes.Buffer) doesn't provide a Close function.

OneOfOne
  • 81,080
  • 16
  • 165
  • 166
  • ioutil.NopCloser only wraps io.Reader. You can create your own equivalent to produce an io.WriteCloser – krait Jan 26 '15 at 22:25
  • 3
    It also has uses where you want to be able to read from it multiple times, without losing the content, as in this example: https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361 – Glenn 'devalias' Grant Feb 06 '19 at 07:32
1

It is for when you need to supply an item that has a Close function, but when Close doesn't really make sense for that item. As such, the function pretty much does nothing:

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

https://github.com/golang/go/blob/go1.16.3/src/io/io.go#L620

halfer
  • 18,701
  • 13
  • 79
  • 158
Steven Penny
  • 82,115
  • 47
  • 308
  • 348