在Go中解压缩tarball

For part of a program I'm writing I have a function for unpacking a tarball and returning a list of its content.

Everything appears to work except the extracted files are empty. I can extract the files content to stdout and see that it does give the correct content, just not sure why its not writing to the files.

The function:

func UnpackTarball(filename, extractpath string) ([]string, error) {
        buf, err := ioutil.ReadFile(filename)
        if err != nil {
                return nil, err
        }

        if err = os.MkdirAll(extractpath, os.ModeDir|0755); err != nil {
                return nil, err
        }

        tarball := tar.NewReader(bytes.NewReader(buf))
        contentlist := make([]string, 0, 500)

        // Iterate through the files in the archive
        for {
                hdr, err := tarball.Next()
                if err == io.EOF {
                        // end of tar archive
                        break
                }
                if err != nil {
                        return nil, err
                }

                info := hdr.FileInfo()
                entry := path.Join(extractpath, hdr.Name)

                // Is entry a directory?
                if info.IsDir() {
                        if err = os.MkdirAll(entry, os.ModeDir|0755); err != nil {
                                return nil, err
                        }
                        continue
                }

                // Append entry to the content list
                contentlist = append(contentlist, hdr.Name)
                // Create file
                f, err := os.Create(entry)
                if err != nil {
                        return nil, err
                }
                defer f.Close()

                _, err = io.Copy(bufio.NewWriter(f), tarball)
                //_, err = io.Copy(os.Stdout, tarball)
                if err != nil {
                        return nil, err
                }
        }
        return contentlist, nil
}

Thanks for any help.

You are not flushing the contents of the buffered writer and consequently you are not writing anything if the files are small enough. Place a call to bufio.(*Writer).Flush() somewhere after your io.Copy() call.

Also, you might want to close the output files in the loop instead of deferring until all files have been written.