Created
April 4, 2026 15:58
-
-
Save crgimenes/cdeb6e79202d4dc90b2914e3f5d254ea to your computer and use it in GitHub Desktop.
merge-zip-files-without-recompression
This file contains hidden or 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/zip" | |
| "fmt" | |
| "io" | |
| "os" | |
| ) | |
| func addZipToWriter(zw *zip.Writer, srcPath string) error { | |
| r, err := zip.OpenReader(srcPath) | |
| if err != nil { | |
| return err | |
| } | |
| defer r.Close() | |
| for _, file := range r.File { | |
| // Open the file to get the raw compressed data | |
| rawReader, err := file.OpenRaw() | |
| if err != nil { | |
| return fmt.Errorf("failed to open raw reader for %s: %w", file.Name, err) | |
| } | |
| // Create a new file in the target zip with the same header | |
| rawWriter, err := zw.CreateRaw(&file.FileHeader) | |
| if err != nil { | |
| return fmt.Errorf("failed to create raw writer for %s: %w", file.Name, err) | |
| } | |
| // Copy the raw compressed data directly from the source to the target | |
| _, err = io.Copy(rawWriter, rawReader) | |
| if err != nil { | |
| return fmt.Errorf("failed to copy raw data for %s: %w", file.Name, err) | |
| } | |
| } | |
| return nil | |
| } | |
| func MergeZips(targetPath string, sources []string) error { | |
| // Create the target zip file | |
| targetFile, err := os.Create(targetPath) | |
| if err != nil { | |
| return fmt.Errorf("failed to create target file: %w", err) | |
| } | |
| defer targetFile.Close() | |
| // Create a new zip writer for the target file | |
| zipWriter := zip.NewWriter(targetFile) | |
| defer zipWriter.Close() | |
| for _, src := range sources { | |
| // Add the contents of each source zip to the target zip | |
| err = addZipToWriter(zipWriter, src) | |
| if err != nil { | |
| return fmt.Errorf("failed processing %s: %w", src, err) | |
| } | |
| } | |
| return nil | |
| } | |
| func main() { | |
| // Usage example: merge "part1.zip" and "part2.zip" into "output.zip" | |
| sources := []string{"part1.zip", "part2.zip"} | |
| output := "output.zip" | |
| fmt.Printf("Merging %v into %s...\n", sources, output) | |
| err := MergeZips(output, sources) | |
| if err != nil { | |
| fmt.Fprintf(os.Stderr, "Error: %v\n", err) | |
| os.Exit(1) | |
| } | |
| fmt.Println("Merge completed successfully.") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment