package main import ( "archive/tar" "bytes" "fmt" ) func main() { // create a new buffer to hold the TAR data buf := new(bytes.Buffer) // create a new TAR writer object tw := tar.NewWriter(buf) // create a new file header hdr := &tar.Header{ Name: "myfile.txt", Mode: 0644, Size: int64(len("This is some content.")), } // write the file header and content to the TAR writer tw.WriteHeader(hdr) tw.Write([]byte("This is some content.")) // get the header size of the file hSize := hdr.Size fmt.Printf("Header size of %s is %d bytes.\n", hdr.Name, hSize) tw.Close() }
package main import ( "archive/tar" "bytes" "fmt" "io" ) func main() { // create a new buffer to hold the TAR data buf := new(bytes.Buffer) // create a new TAR writer object tw := tar.NewWriter(buf) // create a new file header hdr := &tar.Header{ Name: "myfile.txt", Mode: 0644, Size: int64(len("This is some content.")), } // write the file header and content to the TAR writer tw.WriteHeader(hdr) tw.Write([]byte("This is some content.")) tw.Close() // create a new TAR reader object tr := tar.NewReader(buf) // iterate over all files in the TAR archive for { hdr, err := tr.Next() if err == io.EOF { break } if err != nil { fmt.Println("Error:", err) continue } // check if this is the file we are looking for if hdr.Name == "myfile.txt" { // retrieve the header size of the file hSize := hdr.Size fmt.Printf("Header size of %s is %d bytes.\n", hdr.Name, hSize) break } } }Package Library: The package library used in these examples is "archive/tar", which is part of the Go standard library.