io.Reader equivalent of ioutil.Discard

2,278 views
Skip to first unread message

robn...@gmail.com

unread,
Apr 3, 2014, 12:42:09 PM4/3/14
to golan...@googlegroups.com
ioutil.Discard provides a writer that goes nowhere. The ioutil source code includes a reader-version specifically for io.Copy, but doesn't make it public. Is there a standard way to handle this? As an example, I'd like to pass an empty reader to a function that closes the reader (so passing nil would crash). I'm currently using a string reader:

    req, err := http.NewRequest("GET", "...", strings.NewReader(""))

I would expect something like `ioutil.DevNull` instead.

-Rob

James Bardin

unread,
Apr 3, 2014, 1:48:14 PM4/3/14
to golan...@googlegroups.com
If you're certain only Close() will ever be called, you can pass `ioutil.NopCloser(nil)` (Read will still panic, maybe that's what you want.)
Otherwise, a simple devNull with Read is only a few lines to stub out the methods.

voidlogic

unread,
Apr 3, 2014, 2:55:30 PM4/3/14
to golan...@googlegroups.com
Maybe you want: foo := ioutil.NopCloser(bytes.NewReader(nil))

Brad Fitzpatrick

unread,
Apr 3, 2014, 4:08:40 PM4/3/14
to robn...@gmail.com, golang-nuts
You can pass nil to http.NewRequest, btw.



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Rob Napier

unread,
Apr 4, 2014, 4:36:40 PM4/4/14
to Brad Fitzpatrick, golang-nuts
I was confused about my responsibility to close the request body. I see that I don't actually need to do that, so there's no need to worry about it being nil (I was crashing when I added a "defer request.Body.Close(), but that's not needed).

Thanks,
-Rob


Rob Napier

unread,
Apr 4, 2014, 4:54:08 PM4/4/14
to Brad Fitzpatrick, golang-nuts
Note that this does panic if you pass nil to a POST request. I know this is an unusual situation, but I'm writing test cases and am testing the case where a POST is sent with no content. The HTTP spec allows POST without a body (there was a somewhat interesting discussion on the IETF forum about that), so if nil is ok to pass to NewRequest(), it seems it should be legal even for POST.

-Rob
--
Rob Napier -- Software and Security Consulting
Cocoaphony blog -- http://robnapier.net/blog
iOS Programming Pushing the Limits -- http://robnapier.net/book

Brad Fitzpatrick

unread,
Apr 8, 2014, 1:52:38 PM4/8/14
to Rob Napier, golang-nuts
Where do you see a panic with a nil Body?  I can't reproduce that.

Please file a bug if so, with example code?


Reply all
Reply to author
Forward
0 new messages