Golang io / ioutil NopCloser

Does anyone have a good or some explanation for the Golang NopCloser function?
I looked around, but could not find anything but an explanation of the main document of the Golang:

NopCloser returns ReadCloser using the no-op Close method wrapping provided by Reader r.

Any pointers or explanations would be appreciated. Thanks.

+6
source share
2 answers

Whenever you need to return io.ReadCloser , make sure Close() is available, you can use NopCloser to create such a ReaderCloser.

You can see one example in this gorest fork , 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 } 
+11
source

It is used for functions that require io.ReadCloser , but your current object (for example, bytes.Buffer ) does not provide a Close function.

+2
source

Source: https://habr.com/ru/post/981572/


All Articles