Skip to content

Instantly share code, notes, and snippets.

@galargh
Created March 30, 2023 09:34
Show Gist options
  • Save galargh/7a1baec0f679605e0ba3ecc0d7e558fc to your computer and use it in GitHub Desktop.
Save galargh/7a1baec0f679605e0ba3ecc0d7e558fc to your computer and use it in GitHub Desktop.
in-memory tar in Go
package main
import (
"archive/tar"
"fmt"
"io"
"os"
"strings"
"testing/fstest"
)
func MustReadTar(content string) fstest.MapFS {
contentReader := strings.NewReader(content)
tarReader := tar.NewReader(contentReader)
fs := make(fstest.MapFS)
for {
file, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
if file.Typeflag != tar.TypeReg {
continue
}
data, err := io.ReadAll(tarReader)
if err != nil {
panic(err)
}
fs[file.Name] = &fstest.MapFile{Data: data}
}
return fs
}
func main() {
// open tar-example.tar
file, err := os.Open("tar-example.tar")
if err != nil {
panic(err)
}
defer file.Close()
// read file content as string
content, err := io.ReadAll(file)
if err != nil {
panic(err)
}
fs := MustReadTar(string(content))
fmt.Println(fs)
hello, err := fs.ReadFile("tar-example/subdirectory/hello.txt")
if err != nil {
panic(err)
}
fmt.Println(string(hello))
}
#!/usr/bin/env bash
mkdir -p tar-example/subdirectory
tar cf tar-example.tar tar-example
go run tar_reader.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment