### Queue Archive Extraction with xtractr Source: https://github.com/golift/xtractr/blob/main/README.md Demonstrates how to use the xtractr library to queue archive files for extraction. It sets up a custom logger, creates a new extraction queue with specified configurations, and sends an archive to the queue. The code then listens for responses, logging the start and completion of the extraction process, including any errors and the list of extracted files. This method is suitable for batch processing archives. ```golang package main import ( "log" "os" "strings" "golift.io/xtractr" ) // Logger satisfies the xtractr.Logger interface. type Logger struct { xtractr *log.Logger debug *log.Logger info *log.Logger } // Printf satisfies the xtractr.Logger interface. func (l *Logger) Printf(msg string, v ...interface{}) { l.xtractr.Printf(msg, v...) } // Debug satisfies the xtractr.Logger interface. func (l *Logger) Debugf(msg string, v ...interface{}) { l.debug.Printf(msg, v...) } // Infof printf an info line. func (l *Logger) Infof(msg string, v ...interface{}) { l.info.Printf(msg, v...) } func main() { log := &Logger{ xtractr: log.New(os.Stdout, "[XTRACTR] ", 0), debug: log.New(os.Stdout, "[DEBUG] ", 0), info: log.New(os.Stdout, "[INFO] ", 0), } q := xtractr.NewQueue(&xtractr.Config{ Suffix: "_xtractd", Logger: log, Parallel: 1, FileMode: 0644, // ignored for tar files. DirMode: 0755, }) defer q.Stop() // Stop() waits until all extractions finish. response := make(chan *xtractr.Response) // This sends an item into the extraction queue (buffered channel). q.Extract(&xtractr.Xtract{ Name: "my archive", // name is not import to this library. SearchPath: "/tmp/archives", // can also be a direct file. CBChannel: response, // queue responses are sent here. }) // Queue always sends two responses. 1 on start and again when finished (error or not) resp := <-response log.Infof("Extraction started: %s", strings.Join(resp.Archives, ", ")) resp = <-response if resp.Error != nil { // There is possibly more data in the response that is useful even on error. // ie you may want to cleanup any partial extraction. log.Printf("Error: %v", resp.Error) } log.Infof("Extracted Files:\n - %s", strings.Join(resp.NewFiles, "\n - ")) } ``` -------------------------------- ### Manage Files and Extract Archives with Xtractr in Go Source: https://context7.com/golift/xtractr/llms.txt Demonstrates using Xtractr's Queue for file listing before and after extraction, detecting new files, moving them, and cleaning up. It requires the xtractr package and standard Go libraries like 'fmt', 'log', and 'os'. ```go package main import ( "fmt" "log" "golift.io/xtractr" "os" ) type Logger struct{} func (l *Logger) Printf(msg string, v ...interface{}) { log.Printf(msg, v...) } func (l *Logger) Debugf(msg string, v ...interface{}) {} func main() { q := xtractr.NewQueue(&xtractr.Config{ Logger: &Logger{}, Parallel: 1, }) defer q.Stop() // Get file list before extraction before, err := q.GetFileList("/tmp/target") if err != nil { log.Fatal(err) } // Extract archive x := &xtractr.XFile{ FilePath: "/tmp/archive.zip", OutputDir: "/tmp/target", } xtractr.ExtractFile(x) // Get file list after extraction after, err := q.GetFileList("/tmp/target") if err != nil { log.Fatal(err) } // Find newly extracted files newFiles := xtractr.Difference(before, after) fmt.Printf("Newly extracted files:\n") for _, file := range newFiles { fmt.Printf(" - %s\n", file) } // Move files to new location movedFiles, err := q.MoveFiles("/tmp/target", "/tmp/final", false) if err != nil { log.Printf("Move error: %v", err) } fmt.Printf("Moved %d files\n", len(movedFiles)) // Clean up q.DeleteFiles("/tmp/target/unwanted.txt", "/tmp/target/temp") } ``` -------------------------------- ### Queue-Based Archive Extraction with Callbacks Go Source: https://context7.com/golift/xtractr/llms.txt Sets up a queue for concurrent archive extraction with callback notifications for progress and completion. Allows configuring parallelism, logging, and buffer size. Uses a custom logger implementing xtractr.Logger and a channel to receive extraction responses. Supports filtering archives by path and depth, and options for deleting original files or using temporary folders. ```go package main import ( "log" "os" "strings" "golift.io/xtractr" ) // Custom logger implementing xtractr.Logger interface type Logger struct { xtractr *log.Logger debug *log.Logger } func (l *Logger) Printf(msg string, v ...interface{}) { l.xtractr.Printf(msg, v...) } func (l *Logger) Debugf(msg string, v ...interface{}) { l.debug.Printf(msg, v...) } func main() { // Create logger logger := &Logger{ xtractr: log.New(os.Stdout, "[XTRACTR] ", 0), debug: log.New(os.Stdout, "[DEBUG] ", 0), } // Configure extraction queue q := xtractr.NewQueue(&xtractr.Config{ Suffix: "_extracted", Logger: logger, Parallel: 2, // 2 concurrent extractions FileMode: 0644, DirMode: 0755, BuffSize: 100, // Queue buffer size }) defer q.Stop() // Create response channel response := make(chan *xtractr.Response) // Queue extraction queueSize, err := q.Extract(&xtractr.Xtract{ Name: "monthly-archives", Filter: xtractr.Filter{ Path: "/tmp/archives", MaxDepth: 2, }, CBChannel: response, DeleteOrig: false, TempFolder: true, }) if err != nil { log.Fatalf("Failed to queue: %v", err) } log.Printf("Queue size: %d", queueSize) // First response: extraction started resp := <-response if !resp.Done { log.Printf("Extraction started: %s", strings.Join(resp.Archives.List(), ", ")) } // Second response: extraction completed resp = <-response if resp.Done { if resp.Error != nil { log.Printf("Error: %v (took %v)", resp.Error, resp.Elapsed) } else { log.Printf("Success! Extracted %d bytes in %v", resp.Size, resp.Elapsed) log.Printf("Files: %s", strings.Join(resp.NewFiles, ", ")) } } } ``` -------------------------------- ### Queue-Based Extraction with Callbacks Source: https://context7.com/golift/xtractr/llms.txt Implement concurrent extraction of multiple archives using a queue system. Provides callback notifications for progress and completion. ```APIDOC ## Queue-Based Extraction with Callbacks ### Description Create an extraction queue for concurrent processing with callback notifications. This allows for handling multiple archives simultaneously and monitoring their status. ### Method `NewQueue` and `Extract` (from `golift.io/xtractr` package) ### Parameters #### `xtractr.Config` (for `NewQueue`) - **Suffix** (string) - Optional - A suffix to append to extracted file names. - **Logger** (xtractr.Logger) - Optional - A custom logger implementation to capture library logs. - **Parallel** (int) - Optional - The number of concurrent extractions to perform (defaults to 1). - **FileMode** (os.FileMode) - Optional - The file mode to apply to extracted files (default: 0644). - **DirMode** (os.FileMode) - Optional - The directory mode to apply to created directories (default: 0755). - **BuffSize** (int) - Optional - The buffer size for the extraction queue. #### `xtractr.Xtract` (for `Extract`) - **Name** (string) - Required - A name for this extraction job. - **Filter** (xtractr.Filter) - Required - Defines the archives to be extracted. - **Path** (string) - Required - The directory to scan for archives. - **MaxDepth** (int) - Optional - Maximum recursion depth for finding archives. - **CBChannel** (chan *xtractr.Response) - Required - A channel to receive extraction responses. - **DeleteOrig** (bool) - Optional - Whether to delete original archive files after successful extraction. - **TempFolder** (bool) - Optional - Whether to use a temporary folder for extraction. ### Request Example ```go package main import ( "log" "os" "strings" "golift.io/xtractr" ) // Custom logger implementing xtractr.Logger interface type Logger struct { xtractr *log.Logger debug *log.Logger } func (l *Logger) Printf(msg string, v ...interface{}) { l.xtractr.Printf(msg, v...) } func (l *Logger) Debugf(msg string, v ...interface{}) { l.debug.Printf(msg, v...) } func main() { // Create logger logger := &Logger{ xtractr: log.New(os.Stdout, "[XTRACTR] ", 0), debug: log.New(os.Stdout, "[DEBUG] ", 0), } // Configure extraction queue q := xtractr.NewQueue(&xtractr.Config{ Suffix: "_extracted", Logger: logger, Parallel: 2, // 2 concurrent extractions FileMode: 0644, DirMode: 0755, BuffSize: 100, // Queue buffer size }) defer q.Stop() // Create response channel response := make(chan *xtractr.Response) // Queue extraction queueSize, err := q.Extract(&xtractr.Xtract{ Name: "monthly-archives", Filter: xtractr.Filter{ Path: "/tmp/archives", MaxDepth: 2, }, CBChannel: response, DeleteOrig: false, TempFolder: true, }) if err != nil { log.Fatalf("Failed to queue: %v", err) } log.Printf("Queue size: %d", queueSize) // First response: extraction started resp := <-response if !resp.Done { log.Printf("Extraction started: %s", strings.Join(resp.Archives.List(), ", ")) } // Second response: extraction completed resp = <-response if resp.Done { if resp.Error != nil { log.Printf("Error: %v (took %v)", resp.Error, resp.Elapsed) } else { log.Printf("Success! Extracted %d bytes in %v", resp.Size, resp.Elapsed) log.Printf("Files: %s", strings.Join(resp.NewFiles, ", ")) } } } ``` ### Response #### Success Response (200) - **response** (channel *xtractr.Response) - A channel that receives `xtractr.Response` structs. - **Done** (bool) - Indicates if the extraction process for this batch is completed. - **Error** (error) - Any error encountered during extraction. - **Size** (int64) - Total size of successfully extracted files. - **Elapsed** (time.Duration) - The time taken for the extraction. - **NewFiles** ([]string) - A list of newly created files after extraction. - **Archives** (xtractr.ArchiveList) - List of archives that were processed in this batch. #### Response Example (Initial) ``` Extraction started: archive1.zip, archive2.rar ``` #### Response Example (Completion) ``` Success! Extracted 102400 bytes in 1.5s Files: fileA.txt, folder/fileB.txt ``` #### Response Example (Error) ``` Error: archive.zip: uncorrect password (took 500ms) ``` ``` -------------------------------- ### Configure Recursion and ISO Handling Source: https://context7.com/golift/xtractr/llms.txt Configure extraction behavior for nested archives and ISO files. This snippet demonstrates advanced queue configuration, including setting parallelism, buffer size, file modes, and custom suffixes. It also shows how to control recursion depth, exclude specific file types, and handle password-protected archives. ```go package main import ( "log" "os" "golift.io/xtractr" ) type SimpleLogger struct{} func (l *SimpleLogger) Printf(msg string, v ...interface{}) { log.Printf(msg, v...) } func (l *SimpleLogger) Debugf(msg string, v ...interface{}) { // Suppress debug logs } func main() { q := xtractr.NewQueue(&xtractr.Config{ Logger: &SimpleLogger{}, Parallel: 4, BuffSize: 500, FileMode: 0644, DirMode: 0755, Suffix: "_unpacked", TryNames: true, }) defer q.Stop() response := make(chan *xtractr.Response) // Extract with nested archive handling q.Extract(&xtractr.Xtract{ Name: "nested-archives", Filter: xtractr.Filter{ Path: "/data/nested", MaxDepth: 2, ExcludeSuffix: xtractr.Exclude{}.Append(".txt", ".log"), }, Password: "default_pass", Passwords: []string{"pass1", "pass2", "pass3"}, DisableRecursion: false, // Extract nested archives RecurseISO: true, // Also recurse into ISO files TempFolder: false, // Move files back to source DeleteOrig: true, // Delete archives after extraction LogFile: true, // Create extraction log CBChannel: response, }) // Wait for start <-response // Wait for completion resp := <-response if resp.Error == nil { log.Printf("Extracted %d archives + %d nested archives", resp.Archives.Count(), resp.Extras.Count()) log.Printf("Total size: %d bytes in %v", resp.Size, resp.Elapsed) // Log extracted archives for dir, files := range resp.Archives { log.Printf("From %s:", dir) for _, file := range files { log.Printf(" - %s", file) } } } } ``` -------------------------------- ### Manage Queues with Callbacks Source: https://context7.com/golift/xtractr/llms.txt Demonstrates how to manage extraction queues using function callbacks instead of channels. This approach is useful for asynchronous processing where immediate channel feedback isn't required. The callback function receives a response object containing extraction status, errors, and details. ```go package main import ( "log" "os" "golift.io/xtractr" ) type Logger struct { logger *log.Logger } func (l *Logger) Printf(msg string, v ...interface{}) { l.logger.Printf(msg, v...) } func (l *Logger) Debugf(msg string, v ...interface{}) { l.logger.Printf("[DEBUG] "+msg, v...) } func extractionCallback(resp *xtractr.Response) { if !resp.Done { log.Printf("Started: %s (Queue: %d)", resp.X.Name, resp.Queued) return } if resp.Error != nil { log.Printf("Failed: %s - %v", resp.X.Name, resp.Error) return } log.Printf("Completed: %s", resp.X.Name) log.Printf(" Duration: %v", resp.Elapsed) log.Printf(" Size: %d bytes", resp.Size) log.Printf(" Files: %d", len(resp.NewFiles)) log.Printf(" Extras: %d", resp.Extras.Count()) } func main() { logger := &Logger{logger: log.New(os.Stdout, "[XTRACTR] ", log.LstdFlags)} q := xtractr.NewQueue(&xtractr.Config{ Logger: logger, Parallel: 3, FileMode: 0644, DirMode: 0755, TryNames: true, // Auto-rename if output exists }) defer q.Stop() // Queue multiple extractions archives := []string{ "/tmp/archive1.zip", "/tmp/archive2.rar", "/tmp/archive3.7z", } for _, archive := range archives { q.Extract(&xtractr.Xtract{ Name: archive, Filter: xtractr.Filter{ Path: archive, }, CBFunction: extractionCallback, DisableRecursion: false, TempFolder: true, DeleteOrig: false, LogFile: true, }) } log.Println("All extractions queued") } ``` -------------------------------- ### Flatten Archive Structure with Xtractr's SquashRoot in Go Source: https://context7.com/golift/xtractr/llms.txt Illustrates Xtractr's SquashRoot feature to flatten archives with a single root directory, preventing unnecessary nesting. It demonstrates setting file/directory modes and using a custom logger. Requires the xtractr package. ```go package main import ( "log" "golift.io/xtractr" ) func main() { // Without SquashRoot: archive extracts to /tmp/output/archive_name/files // With SquashRoot: if only one root dir, content moves to /tmp/output/files x := &xtractr.XFile{ FilePath: "/tmp/nested.zip", OutputDir: "/tmp/output", SquashRoot: true, // Flatten single root directory FileMode: 0644, DirMode: 0755, } size, files, err := xtractr.ExtractFile(x) if err != nil { log.Fatalf("Extraction failed: %v", err) } log.Printf("Extracted %d bytes to %d files", size, len(files)) log.Println("Archive structure flattened (if single root directory)") // Also works with logger for debugging type CustomLogger struct{} func (l *CustomLogger) Printf(msg string, v ...interface{}) { log.Printf("[XTRACTR] "+msg, v...) } func (l *CustomLogger) Debugf(msg string, v ...interface{}) { log.Printf("[DEBUG] "+msg, v...) } x2 := &xtractr.XFile{ FilePath: "/tmp/another.tar.gz", OutputDir: "/tmp/output2", SquashRoot: true, } x2.SetLogger(&CustomLogger{}) size, files, err = x2.Extract() if err != nil { log.Fatalf("Failed: %v", err) } } ``` -------------------------------- ### Direct Archive Extraction with xtractr.ExtractFile Source: https://github.com/golift/xtractr/blob/main/README.md Shows how to use the `ExtractFile` function for direct decompression and extraction of a single archive file. It requires an `XFile` struct containing the file path and output directory. The function attempts to auto-detect the archive type and returns the total size written, a list of extracted files, and any error encountered. Failing to specify `OutputDir` can lead to unexpected results. Specific extraction functions like `ExtractZIP` are also available. ```golang package main import ( "log" "strings" "golift.io/xtractr" ) func main() { x := &xtractr.XFile{ FilePath: "/tmp/myfile.zip", OutputDir: "/tmp/myfile", // do not forget this. } // size is how many bytes were written. // files may be nil, but will contain any files written (even with an error). size, files, err := xtractr.ExtractFile(x) if err != nil || files == nil { log.Fatal(size, files, err) } log.Println("Bytes written:", size, "Files Extracted:\n -", strings.Join(files, "\n - ")) } ``` -------------------------------- ### Decompress Single Compressed Files (Gzip, Bzip2, XZ, Zstandard, LZ4) Source: https://context7.com/golift/xtractr/llms.txt This snippet demonstrates how to decompress individual compressed files that are not archives, using functions like `ExtractGzip`, `ExtractBzip`, `ExtractXZ`, `ExtractZstandard`, and `ExtractLZ4`. Similar to archive extraction, these functions utilize the `xtractr.XFile` struct to define input and output paths and optional file modes. They return the decompressed size, a list of resulting files, and any encountered errors. ```go package main import ( "log" "golift.io/xtractr" ) func main() { // Extract Gzip file gzFile := &xtractr.XFile{ FilePath: "/tmp/document.txt.gz", OutputDir: "/tmp/output", FileMode: 0644, DirMode: 0755, } size, files, err := xtractr.ExtractGzip(gzFile) if err != nil { log.Fatalf("Gzip extraction failed: %v", err) } log.Printf("Decompressed to: %s (%d bytes)", files[0], size) // Extract Bzip2 file bz2File := &xtractr.XFile{ FilePath: "/tmp/data.bz2", OutputDir: "/tmp/output", } size, files, err = xtractr.ExtractBzip(bz2File) // Extract XZ file xzFile := &xtractr.XFile{ FilePath: "/tmp/archive.xz", OutputDir: "/tmp/output", } size, files, err = xtractr.ExtractXZ(xzFile) // Extract Zstandard file zstdFile := &xtractr.XFile{ FilePath: "/tmp/data.zst", OutputDir: "/tmp/output", } size, files, err = xtractr.ExtractZstandard(zstdFile) // Extract LZ4 file lz4File := &xtractr.XFile{ FilePath: "/tmp/data.lz4", OutputDir: "/tmp/output", } size, files, err = xtractr.ExtractLZ4(lz4File) log.Printf("All decompression operations complete") } ``` -------------------------------- ### Extract Specific Archive Formats (ZIP, RAR, TAR.GZ, 7Z) Source: https://context7.com/golift/xtractr/llms.txt This snippet shows how to extract various archive formats using specific functions like `ExtractZIP`, `ExtractRAR`, `ExtractTarGzip`, and `Extract7z`. These functions take an `xtractr.XFile` struct as input, which specifies the archive path, output directory, and optional parameters like password and file permissions. They return the total extracted size, a list of extracted files, and an error if the operation fails. RAR and 7Z extraction can also return a list of archive parts. ```go package main import ( "log" "golift.io/xtractr" ) func main() { // Extract ZIP zipFile := &xtractr.XFile{ FilePath: "/tmp/data.zip", OutputDir: "/tmp/zip_out", FileMode: 0644, DirMode: 0755, } size, files, err := xtractr.ExtractZIP(zipFile) if err != nil { log.Fatalf("ZIP extraction failed: %v", err) } // Extract RAR with password rarFile := &xtractr.XFile{ FilePath: "/tmp/data.rar", OutputDir: "/tmp/rar_out", Password: "mypassword", FileMode: 0644, DirMode: 0755, } size, files, archives, err := xtractr.ExtractRAR(rarFile) log.Printf("Extracted %d bytes from %d archives", size, len(archives)) // Extract TAR.GZ tarFile := &xtractr.XFile{ FilePath: "/tmp/backup.tar.gz", OutputDir: "/tmp/tar_out", FileMode: 0644, DirMode: 0755, } size, files, err = xtractr.ExtractTarGzip(tarFile) // Extract 7Z multi-volume archive sevenZFile := &xtractr.XFile{ FilePath: "/tmp/archive.7z.001", OutputDir: "/tmp/7z_out", Password: "secret", FileMode: 0644, DirMode: 0755, } size, files, archives, err = xtractr.Extract7z(sevenZFile) log.Printf("All extractions complete: %d files", len(files)) } ``` -------------------------------- ### Check Archive Support and Extensions Source: https://context7.com/golift/xtractr/llms.txt Verify if a given file is a supported archive format and retrieve a list of all supported file extensions. This utility function is essential for pre-processing files before attempting extraction, saving resources by skipping unsupported types. It also provides a mechanism to create exclusion lists based on supported formats. ```go package main import ( "fmt" "golift.io/xtractr" ) func main() { // Check if file is an archive files := []string{ "/tmp/data.zip", "/tmp/document.txt", "/tmp/backup.tar.gz", "/tmp/image.iso", } for _, file := range files { if xtractr.IsArchiveFile(file) { fmt.Printf("%s is a supported archive\n", file) } else { fmt.Printf("%s is NOT an archive\n", file) } } // Get all supported extensions extensions := xtractr.SupportedExtensions() fmt.Println("\nSupported archive formats:") for _, ext := range extensions { fmt.Printf(" %s\n", ext) } // Create exclusion list (all except ZIP) excludeAll := xtractr.AllExcept(".zip", ".7z") fmt.Printf("\nExcluding %d formats\n", len(excludeAll)) } ``` -------------------------------- ### Direct File Extraction Source: https://context7.com/golift/xtractr/llms.txt Extract a single archive file directly to a specified output directory. This method is suitable for immediate decompression needs. ```APIDOC ## Direct File Extraction ### Description Extract a single archive file directly to a specified output directory. ### Method `ExtractFile` (from `golift.io/xtractr` package) ### Parameters #### Request Body (xtractr.XFile) - **FilePath** (string) - Required - The path to the archive file to be extracted. - **OutputDir** (string) - Required - The directory where extracted files will be placed. - **Password** (string) - Optional - The password for password-protected archives (use for single password attempt). - **Passwords** ([]string) - Optional - A list of passwords to attempt for password-protected archives. - **FileMode** (os.FileMode) - Optional - The file mode to apply to extracted files (default: 0644). - **DirMode** (os.FileMode) - Optional - The directory mode to apply to created directories (default: 0755). ### Request Example ```go package main import ( "log" "strings" "golift.io/xtractr" ) func main() { // Create extraction configuration x := &xtractr.XFile{ FilePath: "/tmp/archive.zip", OutputDir: "/tmp/extracted", FileMode: 0644, DirMode: 0755, } // Extract the file size, files, err := xtractr.ExtractFile(x) if err != nil { log.Fatalf("Extraction failed: %v", err) } log.Printf("Extracted %d bytes\n", size) log.Printf("Files extracted:\n - %s\n", strings.Join(files, "\n - ")) } ``` ### Response #### Success Response (200) - **size** (int64) - The total size of extracted files in bytes. - **files** ([]string) - A list of the names of the extracted files. #### Response Example ``` Extracted 12345 bytes Files extracted: - file1.txt - folder/file2.txt ``` ``` -------------------------------- ### Extract Single Archive File Go Source: https://context7.com/golift/xtractr/llms.txt Directly extracts a single archive file to a specified output directory. Requires the archive path, output directory, and optional file/directory modes. Returns the total extracted size and a list of extracted files, or an error. ```go package main import ( "log" "strings" "golift.io/xtractr" ) func main() { // Create extraction configuration x := &xtractr.XFile{ FilePath: "/tmp/archive.zip", OutputDir: "/tmp/extracted", FileMode: 0644, DirMode: 0755, } // Extract the file size, files, err := xtractr.ExtractFile(x) if err != nil { log.Fatalf("Extraction failed: %v", err) } log.Printf("Extracted %d bytes\n", size) log.Printf("Files extracted:\n - %s\n", strings.Join(files, "\n - ")) } ``` -------------------------------- ### Password-Protected Archive Extraction Source: https://context7.com/golift/xtractr/llms.txt Handles extraction of archives that are protected by a password, supporting both single and multiple password attempts. ```APIDOC ## Password-Protected Archive Extraction ### Description Extract password-protected RAR or 7Z archives with single or multiple password attempts. ### Method `ExtractFile` (from `golift.io/xtractr` package) ### Parameters #### Request Body (xtractr.XFile) - **FilePath** (string) - Required - The path to the archive file to be extracted. - **OutputDir** (string) - Required - The directory where extracted files will be placed. - **Password** (string) - Optional - The password for password-protected archives (use for single password attempt). - **Passwords** ([]string) - Optional - A list of passwords to attempt for password-protected archives. - **FileMode** (os.FileMode) - Optional - The file mode to apply to extracted files (default: 0644). - **DirMode** (os.FileMode) - Optional - The directory mode to apply to created directories (default: 0755). ### Request Example (Single Password) ```go package main import ( "log" "golift.io/xtractr" ) func main() { // Single password attempt x := &xtractr.XFile{ FilePath: "/tmp/protected.rar", OutputDir: "/tmp/extracted", Password: "secret123", FileMode: 0644, DirMode: 0755, } size, files, err := xtractr.ExtractFile(x) if err != nil { log.Fatalf("Failed with single password: %v", err) } log.Printf("Extracted %d bytes from %d files", size, len(files)) } ``` ### Request Example (Multiple Passwords) ```go package main import ( "log" "golift.io/xtractr" ) func main() { // Multiple password attempts xMulti := &xtractr.XFile{ FilePath: "/tmp/protected.7z", OutputDir: "/tmp/extracted_multi", Passwords: []string{"password1", "password2", "password3"}, FileMode: 0644, DirMode: 0755, } size, files, err := xtractr.ExtractFile(xMulti) if err != nil { log.Fatalf("Failed with multiple passwords: %v", err) } log.Printf("Extracted %d bytes from %d files", size, len(files)) } ``` ### Response #### Success Response (200) - **size** (int64) - The total size of extracted files in bytes. - **files** ([]string) - A list of the names of the extracted files. #### Response Example ``` Extracted 54321 bytes from 5 files ``` ``` -------------------------------- ### Extract Password-Protected Archives Go Source: https://context7.com/golift/xtractr/llms.txt Extracts password-protected RAR or 7Z archives. It supports attempting a single password or a list of passwords. The configuration includes the archive path, output directory, and the password(s). Returns the total extracted size and a list of extracted files, or an error. ```go package main import ( "log" "golift.io/xtractr" ) func main() { // Single password attempt x := &xtractr.XFile{ FilePath: "/tmp/protected.rar", OutputDir: "/tmp/extracted", Password: "secret123", FileMode: 0644, DirMode: 0755, } size, files, err := xtractr.ExtractFile(x) if err != nil { log.Fatalf("Failed with single password: %v", err) } // Multiple password attempts xMulti := &xtractr.XFile{ FilePath: "/tmp/protected.7z", OutputDir: "/tmp/extracted_multi", Passwords: []string{"password1", "password2", "password3"}, FileMode: 0644, DirMode: 0755, } size, files, err = xtractr.ExtractFile(xMulti) if err != nil { log.Fatalf("Failed with multiple passwords: %v", err) } log.Printf("Extracted %d bytes from %d files", size, len(files)) } ``` -------------------------------- ### Find Compressed Archives Recursively with Filters Source: https://context7.com/golift/xtractr/llms.txt This snippet demonstrates how to use `xtractr.FindCompressedFiles` to search for archive files within a directory tree. It supports filtering by depth and exclusion of specific file types. The function returns a map of directories to their found archive files. ```go package main import ( "fmt" "golift.io/xtractr" ) func main() { // Find all archives with depth limits archives := xtractr.FindCompressedFiles(xtractr.Filter{ Path: "/data/downloads", MaxDepth: 3, MinDepth: 1, }) fmt.Printf("Found %d archives\n", archives.Count()) for dir, files := range archives { fmt.Printf("Directory: %s\n", dir) for _, file := range files { fmt.Printf(" - %s\n", file) } } // Find only specific archive types (exclusion list) zipOnly := xtractr.FindCompressedFiles(xtractr.Filter{ Path: "/data/zips", ExcludeSuffix: xtractr.AllExcept(".zip", ".7z"), MaxDepth: 5, }) // Get all archives as a flat list allFiles := zipOnly.List() fmt.Printf("Total ZIP/7Z files: %d\n", len(allFiles)) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.