Created
July 19, 2016 18:14
-
-
Save vbatts/75320e0384bf9e72a6eff219721e07c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"archive/tar" | |
"bytes" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"time" | |
) | |
func main() { | |
buf := new(bytes.Buffer) | |
tw := tar.NewWriter(buf) | |
var files = []struct { | |
Name, Body string | |
}{ | |
{"readme.txt", "This archive contains some text files."}, | |
{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, | |
{"todo.txt", "Get animal handling license."}, | |
} | |
for _, file := range files { | |
hdr := &tar.Header{ | |
Name: file.Name, | |
Mode: 0600, | |
Size: int64(len(file.Body)), | |
ModTime: time.Now(), | |
} | |
fmt.Println(hdr.ModTime.UnixNano()) | |
if err := tw.WriteHeader(hdr); err != nil { | |
log.Fatalln(err) | |
} | |
if _, err := tw.Write([]byte(file.Body)); err != nil { | |
log.Fatalln(err) | |
} | |
} | |
// Make sure to check the error on Close. | |
if err := tw.Close(); err != nil { | |
log.Fatalln(err) | |
} | |
// Open the tar archive for reading. | |
r := bytes.NewReader(buf.Bytes()) | |
tr := tar.NewReader(r) | |
// Iterate through the files in the archive. | |
for { | |
hdr, err := tr.Next() | |
if err == io.EOF { // end of tar archive | |
break | |
} | |
if err != nil { | |
log.Fatalln(err) | |
} | |
fmt.Printf("Contents of %s (%q):\n", hdr.Name, hdr.ModTime.UnixNano()) | |
if _, err := io.Copy(os.Stdout, tr); err != nil { | |
log.Fatalln(err) | |
} | |
fmt.Println() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment