Golang io/ioutil NopCloser

后端 未结 2 1818
时光说笑
时光说笑 2020-12-30 23:44

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:

相关标签:
2条回答
  • 2020-12-31 00:33

    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
            }
    
    0 讨论(0)
  • 2020-12-31 00:43

    It's used for functions that require io.ReadCloser but your current object (for example a bytes.Buffer) doesn't provide a Close function.

    0 讨论(0)
提交回复
热议问题