wrapreader

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2018 License: BSD-3-Clause Imports: 2 Imported by: 1

README

GoDoc Go Report Card

WrapReader

WrapReader is a Go library. It provides an io.ReadCloser that wraps an io.Reader and an io.Closer together.

It's useful when dealing with io.Reader implementations that wraps another io.ReadCloser, but will not close the underlying reader, such as gzip.Reader.

(Example code on godoc)

Documentation

Overview

Package wrapreader provides an io.ReadCloser that wraps an io.Reader and an io.Closer together.

It's useful when dealing with io.Reader implementations that wraps another io.ReadCloser, but will not close the underlying reader, such as GzipReader.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Wrap

func Wrap(reader io.Reader, closer io.Closer) io.ReadCloser

Wrap wraps reader and closer together to create an new io.ReadCloser.

The Read function will simply call the wrapped reader's Read function, while the Close function will call the wrapped closer's Close function.

If the wrapped reader is also an io.Closer, its Close function will be called in Close as well.

Example
package main

import (
	"compress/gzip"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/fishy/wrapreader"
)

func main() {
	filename := filepath.Join(os.TempDir(), "_test.gz")
	content := "Hello, world!"
	defer os.Remove(filename)

	f, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	writer := gzip.NewWriter(f)
	func() {
		defer func() {
			writer.Close()
			f.Close()
		}()
		_, err = writer.Write([]byte(content))
		if err != nil {
			log.Fatal(err)
		}
	}()

	f, err = os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	reader, err := gzip.NewReader(f)
	if err != nil {
		log.Fatal(err)
	}
	readCloser := wrapreader.Wrap(reader, f)
	// readCloser.Close() will close both f and reader
	defer readCloser.Close()
	// Read from readCloser is actually read from reader
	read, err := ioutil.ReadAll(readCloser)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(read))
}
Output:

Hello, world!

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL