Golang io/ioutil NopCloser [英] Golang io/ioutil NopCloser

查看:181
本文介绍了Golang io/ioutil NopCloser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人对Golang的 NopCloser 函数有很好的解释吗?
我环顾四周,但除了Golang主文档对以下内容的解释外,没有找到其他东西:

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返回一个带有非操作Close方法的ReadCloser,该方法包装了 提供了Reader r.

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

任何指针或解释将不胜感激.谢谢.

Any pointers or explanation would be appreciated. Thanks.

推荐答案

每当您需要返回> c1> ,同时确保Close()可用,但您可以使用NopCloser来构建这样的ReaderCloser.

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.

您可以在 gorest叉中看到一个示例. /github.com/fromkeith/gorest/blob/master/util.go"rel =" noreferrer> util.go

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
        }

这篇关于Golang io/ioutil NopCloser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆