有没有人能很好的解释一下Golang的NopCloser
功能?
我环顾四周,除了Golang的主要文档中的解释之外,什么都没有找到:
NoCloser返回一个ReadCloser,其中包含一个no-op-Close方法来包装
如有任何提示或解释,我们将不胜感激.谢谢.
有没有人能很好的解释一下Golang的NopCloser
功能?
我环顾四周,除了Golang的主要文档中的解释之外,什么都没有找到:
NoCloser返回一个ReadCloser,其中包含一个no-op-Close方法来包装
如有任何提示或解释,我们将不胜感激.谢谢.
当你需要返回io.ReadCloser
,同时确保Close()
可用时,你可以使用NopCloser
来构建这样一个ReaderCloser.
你可以在fork of gorest,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
}