Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a compressed tar archives using compress/gzip and archive/tar?

Tags:

go

I'm attempting to create a compressed tar archive using the Go standard library, specifically compress/gzip and archive/tar. I can successfully create a tar archive, but when I try to compress said archive, the resulting tarball can't be decompressed. On OSX, I get "Error 1 - Operation Not Permitted"

To run this code, you'll need a file named foo.txt in the same directory.

package main

import (
    "archive/tar"
    "bytes"
    "compress/gzip"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    var b bytes.Buffer

    // Create a new zip archive.
    w := tar.NewWriter(gzip.NewWriter(&b))

    fi, err := os.Stat("foo.txt")

    if err != nil {
        log.Fatal(err)
    }

    header, err := tar.FileInfoHeader(fi, "")

    if err != nil {
        log.Fatal(err)
    }

    err = w.WriteHeader(header)

    if err != nil {
        log.Fatal(err)
    }

    contents, err := ioutil.ReadFile("foo.txt")

    if err != nil {
        log.Fatal(err)
    }

    _, err = w.Write(contents)

    if err != nil {
        log.Fatal(err)
    }

    err = w.Close()

    // Make sure to check the error on Close.
    err = ioutil.WriteFile("foo.tar.gz", b.Bytes(), 0666)

    if err != nil {
        log.Fatal(err)
    }
}
like image 654
derferman Avatar asked Dec 28 '25 23:12

derferman


1 Answers

You need to close the underlying gzip writer so that it you are guaranteed all bytes are flushed out to the file. Like so:

    // gzip writer
    gz := gzip.NewWriter(f)

    // Create a new tar archive.
    w := tar.NewWriter(gz)

    // add things to the tar archive
    // ...

    // make sure the gzip writer flushes any pending bytes
    if err = gz.Close(); err != nil {
            log.Fatal(err)
    }
like image 106
inconshreveable Avatar answered Dec 31 '25 17:12

inconshreveable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!