import ( "archive/tar" "os" )
// create a new tar archive file, err := os.Create("example.tar") if err != nil { panic(err) } defer file.Close() // create a new tar writer tw := tar.NewWriter(file) defer tw.Close() // create a new file to add to the archive fileToArchive, err := os.Open("example.txt") if err != nil { panic(err) } defer fileToArchive.Close() // get file information info, err := fileToArchive.Stat() if err != nil { panic(err) } // create a new tar header for the file header := &tar.Header{ Name: info.Name(), Mode: int64(info.Mode()), Size: info.Size(), } // write the header to the archive err = tw.WriteHeader(header) if err != nil { panic(err) } // write the file content to the archive _, err = io.Copy(tw, fileToArchive) if err != nil { panic(err) } fmt.Println("Added example.txt to example.tar")
// create a new tar archive file, err := os.Create("example.tar") if err != nil { panic(err) } defer file.Close() // create a new tar writer tw := tar.NewWriter(file) defer tw.Close() // list of files to add to the archive filesToAdd := []string{"file1.txt", "file2.txt", "file3.txt"} // loop through the files and add them to the archive for _, fileName := range filesToAdd { // open the file fileToArchive, err := os.Open(fileName) if err != nil { panic(err) } defer fileToArchive.Close() // get file information info, err := fileToArchive.Stat() if err != nil { panic(err) } // create a new tar header for the file header := &tar.Header{ Name: info.Name(), Mode: int64(info.Mode()), Size: info.Size(), } // write the header to the archive err = tw.WriteHeader(header) if err != nil { panic(err) } // write the file content to the archive _, err = io.Copy(tw, fileToArchive) if err != nil { panic(err) } fmt.Println("Added", fileName, "to example.tar") }The `archive/tar` package is part of the Go standard library.