32

I have an io.Reader that doesn't require closing:

stringReader := strings.NewReader("shiny!")

And I want to pass it to a method that receives an io.ReadCloser

func readAndClose(source io.ReadCloser) {
    ...
}

How do I turn the io.Reader into a io.ReadCloser without specially creating a struct that implements the Close method?

noamt
  • 6,006
  • 2
  • 33
  • 50
  • 7
    FYI: this question has been marked as duplicate, but it's in fact a different question. The answer to both questions is the same though, but that's not a reason to mark the question as a duplicate. ;-) – Prutswonder Mar 12 '19 at 14:42

1 Answers1

52

If you're certain that your io.Reader doesn't require any actual closing, you can wrap it with an ioutil.NopCloser.

Go 1.16 Update

As of version 1.16 ioutil.NopCloser is deprecated.

NopCloser has been moved to io:

stringReader := strings.NewReader("shiny!")
stringReadCloser := io.NopCloser(stringReader)

Go 1.15 and older

From the godoc:

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

So we can apply it like:

stringReader := strings.NewReader("shiny!")
stringReadCloser := ioutil.NopCloser(stringReader)
noamt
  • 6,006
  • 2
  • 33
  • 50
  • 7
    The above is my question and I couldn't find the answer in StackOverflow. I found it buried in some forum posts and I thought it might be nice to share. The "Answer your own question" checkbox does state "share your knowledge, Q&A-style". What's disingenuous about that? – noamt Aug 29 '18 at 13:31
  • 7
    @Adrian as someone who's been around SO for 10 years, you ought to be aware that this community is perfectly fine with answering your own questions. – Yuval Adam Aug 29 '18 at 13:44
  • 3
    First result searching SO for `reader readcloser`: https://stackoverflow.com/questions/28158990/golang-io-ioutil-nopcloser – Adrian Aug 29 '18 at 13:45
  • 1
    everything was already on the internet more than once _before_ SO. so be it. long live closing duplicates. long live duplicates. Thanks, @noamt – Daniel Farrell Oct 17 '20 at 01:41
  • 1
    Whats the way to do this without `iotuil` it is deprecated as of 1.16 golang – Nick Mar 04 '21 at 17:12
  • 1
    @Nick I've updated my answer – noamt Mar 05 '21 at 18:15