Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang io/ioutil NopCloser

Tags:

go

reader

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.

like image 993
G4143 Avatar asked Jan 26 '15 21:01

G4143


People also ask

What does ioutil ReadAll return?

ioutil. ReadAll() returns a byte slice ( []byte ) and not a string (plus an error ).

What is io EOF in Golang?

It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF.


1 Answers

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         } 
like image 85
VonC Avatar answered Oct 04 '22 01:10

VonC