### Install Function Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/install.md Example demonstrating how to use the Install function to check and potentially download yt-dlp, and then print the resolved executable path and version. ```go resolved, err := ytdlp.Install(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Using yt-dlp: %s (version: %s)\n", resolved.Executable, resolved.Version) ``` -------------------------------- ### InstallAll Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/install.md Installs all dependencies (yt-dlp, ffmpeg, ffprobe, bun) concurrently using default options. ```go installs, err := ytdlp.InstallAll(context.Background()) if err != nil { log.Printf("Some installations failed: %v", err) } for _, install := range installs { fmt.Printf("Installed: %s\n", install.Executable) } ``` -------------------------------- ### MustInstallAll Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/install.md Installs all dependencies and panics if an error occurs, ensuring all are installed. ```go installs := ytdlp.MustInstallAll(context.Background()) ``` -------------------------------- ### MustInstall Function Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/install.md Example showing the usage of MustInstall, which ensures yt-dlp is installed by panicking on error. ```go ytdlp.MustInstall(context.Background(), nil) // Safe to use yt-dlp now ``` -------------------------------- ### Working with Progress Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/types.md Example demonstrating how to set up a progress callback function. ```go cmd := ytdlp.New(). ProgressFunc(500*time.Millisecond, func(update ytdlp.ProgressUpdate) { if update.TotalBytes > 0 { fmt.Printf("%s: %.2f%% (ETA: %v)\n", update.Filename, update.Percent(), update.ETA()) } }) ``` -------------------------------- ### SponsorBlock Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example of integrating SponsorBlock functionality. ```go cmd := ytdlp.New(). UseSponsorblock(). SponsorblockRemove("sponsor,intro,outro") ``` -------------------------------- ### Authentication Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example of setting authentication flags for ytdlp. ```go cmd := ytdlp.New(). Username("user@example.com"). Password("password123"). Cookies("/path/to/cookies.txt") ``` -------------------------------- ### Comprehensive go-ytdlp Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md A detailed example showcasing the configuration of numerous flags for the go-ytdlp command builder, including output formatting, video selection, download options, subtitle handling, processing, metadata extraction, rate limiting, and progress reporting. ```go package main import ( "context" "fmt" "time" "github.com/lrstanley/go-ytdlp" ) func main() { // Install dependencies ytdlp.MustInstall(context.Background(), nil) // Build command with comprehensive flags cmd := ytdlp.New(). // Output configuration Format("bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]"). FormatSort("res,ext:mp4:m4a"). Output("% (playlist)s/%(playlist_index)02d - %(title)s.%(ext)s"). // Video selection PlaylistStart(1). PlaylistEnd(10). // Download behavior Continue(). NoOverwrites(). IgnoreErrors(). // Subtitles WriteSubtitle(). SubLangs("en,es,fr"). SubFormat("vtt"). // Processing RecodeVideo("mp4"). EmbedSubtitle(). EmbedThumbnail(). // Metadata WriteInfoJSON(). // Speed limiting RateLimit("1M"). // Workarounds Sleep(2). // Output PrintJSON(). NoProgress(). // Progress tracking ProgressFunc(500*time.Millisecond, func(update ytdlp.ProgressUpdate) { fmt.Printf("[%s] %s - %s\n", update.Status, update.Filename, update.PercentString()) }) // Execute result, err := cmd.Run(context.Background(), "https://www.youtube.com/playlist?list=PLxxxxxx") if err != nil { panic(err) } // Process results if result.ExitCode != 0 { fmt.Printf("Error: %s\n", result.Stderr) return } infos, _ := result.GetExtractedInfo() fmt.Printf("Downloaded %d videos\n", len(infos)) } ``` -------------------------------- ### BuildCommand Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Example of using BuildCommand to get the underlying exec.Cmd for manual execution. ```go cmd := ytdlp.New().FormatSort("res") execCmd := cmd.BuildCommand(context.Background(), "https://example.com/video") // Manually execute if needed execCmd.Run() ``` -------------------------------- ### Best Practice: Always Check for Installation Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Ensures yt-dlp is installed before proceeding. ```go if err := ytdlp.Install(ctx, nil); err != nil { log.Fatal("Failed to ensure yt-dlp is installed:", err) } ``` -------------------------------- ### Post-Processing Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example of configuring post-processing and embedding options. ```go cmd := ytdlp.New(). EmbedSubtitle(). EmbedThumbnail(). Exec("notify-send 'Download complete: %(title)s'") ``` -------------------------------- ### Method Chaining Pattern Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example demonstrating the method chaining pattern for building commands. ```go result, err := ytdlp.New(). PrintJSON(). Format("best"). FormatSort("res"). Output("%(title)s.%(ext)s"). NoOverwrites(). Continue(). WriteSubtitle(). WriteInfoJSON(). EmbedThumbnail(). ProgressFunc(time.Second, progressCallback). Run(ctx, "https://example.com/video") ``` -------------------------------- ### Working with ExtractedInfo Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/types.md Example demonstrating how to fetch and process extracted video information. ```go cmd := ytdlp.New().PrintJSON() result, err := cmd.Run(ctx, "https://youtube.com/watch?v=dQw4w9WgXcQ") if err != nil { panic(err) } infos, err := result.GetExtractedInfo() if err != nil { panic(err) } for _, info := range infos { if info.Title != nil { fmt.Printf("Title: %s\n", *info.Title) } for _, format := range info.Formats { if format.FormatID != nil { fmt.Printf(" Format %s: %sx%s\n", *format.FormatID, format.Width, format.Height) } } if len(info.Subtitles) > 0 { fmt.Printf("Available subtitles: %v\n", reflect.ValueOf(info.Subtitles).MapKeys()) } } ``` -------------------------------- ### Installation and Caching Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/README.md Shows how to install and manage yt-dlp and related binaries using go-ytdlp. ```go // Install with defaults ytdlp.MustInstall(ctx, nil) // Install with options opts := &ytdlp.InstallOptions{ DisableChecksum: true, AllowVersionMismatch: true, } resolved, err := ytdlp.Install(ctx, opts) fmt.Printf("Using: %%s (version: %%s)\n", resolved.Executable, resolved.Version) // Install all dependencies concurrently installs, err := ytdlp.InstallAll(ctx) // Clear cache ytdlp.RemoveInstallCache() ``` -------------------------------- ### Use Appropriate Format Strings Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Provides examples of format strings for selecting video quality and audio. ```go // Best quality MP4 Format("bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]") // Audio only Format("bestaudio/best") // Specific format Format("18") // YouTube 360p ``` -------------------------------- ### Verbosity Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example of setting output verbosity and debug flags. ```go cmd := ytdlp.New(). Verbose(). Progress("% (progress)s") ``` -------------------------------- ### JSON Serialization Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example of loading and saving FlagConfig using JSON. ```go // Load from JSON var config ytdlp.FlagConfig json.Unmarshal(data, &config) // Validate if err := config.Validate(); err != nil { // Handle validation error } // Use cmd := ytdlp.New().SetFlagConfig(&config) // Save to JSON data, _ := json.Marshal(config) ``` -------------------------------- ### ErrMisconfig Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Example demonstrating how to check for and handle ErrMisconfig errors, suggesting installation. ```go result, err := cmd.Run(ctx, "https://example.com/video") if err != nil { if _, ok := ytdlp.IsMisconfigError(err); ok { fmt.Println("yt-dlp executable not found or misconfigured") fmt.Println("Use ytdlp.Install() to download it") } } ``` -------------------------------- ### ProgressUpdate.Duration() Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Example of how to get the duration since the download started, which represents either the elapsed time or the total duration if finished. ```go elapsed := update.Duration() fmt.Printf("Elapsed: %v\n", elapsed) ``` -------------------------------- ### ProgressUpdate.PercentString() Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Example of how to get the download progress formatted as a string percentage. ```go fmt.Printf("Progress: %s\n", update.PercentString()) // Output: Progress: 45.23% ``` -------------------------------- ### Download Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Demonstrates setting flags related to download behavior, including resuming, overwriting, and output naming. ```go cmd := ytdlp.New(). Continue(). Output("% (title)s [%(id)s].%(ext)s"). RateLimit("500k") ``` -------------------------------- ### Audio Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Shows how to configure flags for extracting, formatting, and managing audio tracks. ```go cmd := ytdlp.New(). ExtractAudio(). AudioFormat("mp3"). AudioQuality("192") ``` -------------------------------- ### Thumbnail Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Illustrates setting flags for downloading and converting thumbnails. ```go cmd := ytdlp.New(). WriteThumbnail(). ConvertThumbnails("jpg") ``` -------------------------------- ### Workarounds Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example of setting workaround flags for specific sites or issues. ```go cmd := ytdlp.New(). Sleep(5). MaxSleep(15). GeoBypassCountry("US") ``` -------------------------------- ### Go Get Command Source: https://github.com/lrstanley/go-ytdlp/blob/master/README.md Command to install the go-ytdlp package using Go modules. ```console go get -u github.com/lrstanley/go-ytdlp@latest ``` -------------------------------- ### Video Format Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Demonstrates setting flags for format selection, sorting, and post-processing recoding. ```go cmd := ytdlp.New(). Format("bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]"). FormatSort("res,ext:mp4:m4a"). RecodeVideo("mp4"). RecodeAudio("m4a") ``` -------------------------------- ### String Method Example for Result Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Shows how to get a human-readable string representation of the Result, which includes all output logs with timestamps and masked JSON data. ```go result, _ := cmd.Run(ctx, "https://example.com/video") fmt.Println(result.String()) ``` -------------------------------- ### GetFlagConfig and SetFlagConfig Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Demonstrates retrieving and setting flag configurations for a command. ```go cmd := ytdlp.New().FormatSort("res") config := cmd.GetFlagConfig() // Inspect or modify config cmd.SetFlagConfig(config) ``` ```go config := &ytdlp.FlagConfig{} // Configure config... cmd := ytdlp.New().SetFlagConfig(config) ``` -------------------------------- ### Simple Source: https://github.com/lrstanley/go-ytdlp/blob/master/README.md A simple example demonstrating how to use go-ytdlp to download a YouTube video. ```go package main import ( "context" "github.com/lrstanley/go-ytdlp" ) func main() { // If yt-dlp isn't installed yet, download and cache it for further use. ytdlp.MustInstall(context.TODO(), nil) dl := ytdlp.New(). FormatSort("res,ext:mp4:m4a"). RecodeVideo("mp4"). Output("%(extractor)s - %(title)s.%(ext)s") _, err := dl.Run(context.TODO(), "https://www.youtube.com/watch?v=dQw4w9WgXcQ") if err != nil { panic(err) } } ``` -------------------------------- ### Filesystem Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Shows how to configure filesystem-related flags for restricting filenames, loading URLs from files, and managing metadata. ```go cmd := ytdlp.New(). Restrict("on_windows"). WriteInfo("json"). Chmod("644") ``` -------------------------------- ### FlagConfig Direct Usage Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Example of directly using FlagConfig for programmatic configuration. ```go config := &ytdlp.FlagConfig{ General: ytdlp.FlagsGeneral{ NoAbortOnError: ptr(true), }, Download: ytdlp.FlagsDownload{ NoOverwrites: ptr(true), }, VideoFormat: ytdlp.FlagsVideoFormat{ Format: ptr("best[ext=mp4]"), }, } cmd := ytdlp.New().SetFlagConfig(config) result, err := cmd.Run(ctx, "https://example.com/video") ``` -------------------------------- ### Run Method Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Invokes yt-dlp with the provided arguments and any flags previously set via builder methods. The args parameter typically contains URLs to download. ```go cmd := ytdlp.New(). FormatSort("res,ext:mp4:m4a"). Output("% (title)s.%(ext)s") result, err := cmd.Run(context.Background(), "https://www.youtube.com/watch?v=dQw4w9WgXcQ") if err != nil { log.Fatal(err) } ``` -------------------------------- ### StderrFunc Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Example of registering a callback function to receive stderr output. ```go cmd := ytdlp.New(). StderrFunc(func(line string) { log.Println("ffmpeg:", line) }) ``` -------------------------------- ### ErrExitCode Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Example demonstrating how to check for and handle ErrExitCode errors. ```go result, err := cmd.Run(ctx, "https://example.com/video") if err != nil { if errExit, ok := ytdlp.IsExitCodeError(err); ok { fmt.Printf("yt-dlp exited with code %d\n", errExit.result.ExitCode) } } ``` -------------------------------- ### ProgressUpdate.Percent() Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Example of how to retrieve the download progress as a percentage (0-100). ```go fmt.Printf("Progress: %.1f%%\n", update.Percent()) ``` -------------------------------- ### General Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Demonstrates setting general flags like ignoring errors, setting verbosity, and selecting extractors. ```go cmd := ytdlp.New(). IgnoreErrors(). Quiet(). UseExtractors("youtube,vimeo") ``` -------------------------------- ### ProgressFunc Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Registers a callback function to receive progress updates during download. ```go cmd := ytdlp.New(). ProgressFunc(500*time.Millisecond, func(update ytdlp.ProgressUpdate) { fmt.Printf("Downloading: %s (%.2f%%)\n", update.Filename, update.Percent()) }) ``` -------------------------------- ### ProgressUpdate.ETA() Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Example demonstrating how to calculate and display the estimated time remaining for a download. ```go remaining := update.ETA() fmt.Printf("Estimated completion in: %v\n", remaining) ``` -------------------------------- ### Network Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Shows how to configure network-related flags such as proxy and socket timeout. ```go cmd := ytdlp.New(). Proxy("socks5://127.0.0.1:1080"). SocketTimeout(30) ``` -------------------------------- ### ErrParsing Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Example demonstrating how to check for and handle ErrParsing errors, suggesting reinstallation. ```go result, err := cmd.Run(ctx, url) if err != nil { if _, ok := ytdlp.IsParsingError(err); ok { fmt.Println("Flag parsing error - version mismatch likely") fmt.Println("Try reinstalling yt-dlp with ytdlp.Install()") } } ``` -------------------------------- ### Clone Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Creates a deep copy of the command with all flags, environment variables, executable path, working directory, and callbacks copied over. ```go cmd1 := ytdlp.New(). FormatSort("res"). NoPlaylist() cmd2 := cmd1.Clone() cmd2.Playlist() // Only affects cmd2 ``` -------------------------------- ### Subtitle Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Illustrates setting flags for downloading, selecting, and converting subtitles. ```go cmd := ytdlp.New(). WriteSubtitle(). SubLangs("en,fr,de"). SubFormat("vtt"). ConvertSubs("srt") ``` -------------------------------- ### Basic Error Checking Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md A simple example of checking for errors after running a command. ```go result, err := cmd.Run(ctx, "https://example.com/video") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Usage Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md A complete Go program demonstrating how to use the go-ytdlp library to download a video, monitor progress with a callback function, and retrieve extracted information. ```go package main import ( "context" "fmt" "time" "github.com/lrstanley/go-ytdlp" ) func main() { cmd := ytdlp.New(). PrintJSON(). FormatSort("res"). ProgressFunc(1*time.Second, func(update ytdlp.ProgressUpdate) { fmt.Printf("[%s] %s - %s (%.0f%%)\n", update.Status, update.Filename, update.PercentString(), update.ETA().Seconds()) }) result, err := cmd.Run(context.Background(), "https://example.com/video") if err != nil { panic(err) } // Check execution status if result.ExitCode != 0 { fmt.Printf("Error: %s\n", result.Stderr) return } // Extract structured data infos, err := result.GetExtractedInfo() if err != nil { panic(err) } for _, info := range infos { fmt.Printf("Downloaded: %s\n", *info.Title) } } ``` -------------------------------- ### Video Selection Flags Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/flagconfig.md Illustrates setting flags for selecting specific videos or ranges within a playlist. ```go cmd := ytdlp.New(). PlaylistStart(2). PlaylistEnd(5) ``` -------------------------------- ### FlagConfig Validation Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Example of validating a FlagConfig and handling multiple parsing errors. ```go config := &ytdlp.FlagConfig{} // ... set config fields ... if err := config.Validate(); err != nil { if errMulti, ok := ytdlp.IsMultipleJSONParsingFlagsError(err); ok { for _, flagErr := range errMulti.Errors { fmt.Printf("Error at %s: %s\n", flagErr.JSONPath, flagErr.Error()) } } else { log.Fatal(err) } } ``` -------------------------------- ### Flag Setter Methods Examples Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Demonstrates various flag setter methods including boolean flags, flags with arguments, and unset methods. ```go cmd := ytdlp.New(). PrintJSON(). NoPlaylist(). FormatSort("res,ext:mp4:m4a"). Output("%(title)s.%(ext)s"). RecodeVideo("mp4") // Unset a previously set flag cmd.UnsetRecodeVideo() // Get version information (action method) result, err := cmd.Version(context.Background()) ``` -------------------------------- ### Optimize for Large Playlists Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md An example of optimizing command execution for large playlists by setting quality, skipping unavailable items, rate limiting, and enabling parallel downloads. ```go cmd := ytdlp.New(). Format("worst"). // Low quality NoWriteThumbnail(). // Skip thumbnails SkipUnavailable(). // Skip missing videos Sleep(2). // Rate limit Parallel(5) // Download 5 at once ``` -------------------------------- ### Extract Video Information Only Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Get video metadata without downloading. ```go package main import ( "context" "encoding/json" "fmt" "github.com/lrstanley/go-ytdlp" ) func main() { ytdlp.MustInstall(context.Background(), nil) result, err := ytdlp.New(). PrintJSON(). DumpSingleJSON(). SkipDownload(). Run(context.Background(), "https://example.com/video") if err != nil { panic(err) } infos, err := result.GetExtractedInfo() if err != nil { panic(err) } // Pretty-print video info for _, info := range infos { data, _ := json.MarshalIndent(info, "", " ") fmt.Println(string(data)) } } ``` -------------------------------- ### SetExecutable Method Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Sets the path to the yt-dlp executable. If not set, the executable will be resolved from the cache or system PATH. ```go cmd := ytdlp.New().SetExecutable("/usr/local/bin/yt-dlp") ``` -------------------------------- ### Example Usage of IsMultipleJSONParsingFlagsError Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Demonstrates how to check for and handle ErrMultipleJSONParsingFlags errors. ```go if err := config.Validate(); err != nil { if errMulti, ok := ytdlp.IsMultipleJSONParsingFlagsError(err); ok { fmt.Printf("Found %d validation errors:\n", len(errMulti.Errors)) for _, e := range errMulti.Errors { fmt.Printf(" - %s\n", e.Error()) } } } ``` -------------------------------- ### SetEnvVarInherit Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Sets whether the yt-dlp command should inherit environment variables from the parent process. ```go cmd := ytdlp.New().SetEnvVarInherit(false) ``` -------------------------------- ### SetWorkDir Method Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Sets the working directory for the yt-dlp command. Downloaded files will be saved relative to this directory. ```go cmd := ytdlp.New().SetWorkDir("/tmp/downloads") ``` -------------------------------- ### String Method Example for ResultLog Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Illustrates how to format a ResultLog into a human-readable string, including the timestamp and pipe designation. ```go for _, log := range result.OutputLogs { fmt.Println(log.String()) // Output: [2024-01-15::12:34:56::stdout] Download progress 45% } ``` -------------------------------- ### SetCancelMaxWait Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Sets the maximum wait time before the command is forcefully killed after the context is cancelled. ```go cmd := ytdlp.New().SetCancelMaxWait(5 * time.Second) ``` -------------------------------- ### Type-Specific Error Handling Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Demonstrates handling different types of errors returned by yt-dlp. ```go result, err := cmd.Run(ctx, url) if err != nil { if errExit, ok := ytdlp.IsExitCodeError(err); ok { fmt.Printf("yt-dlp exited with code %d\n", errExit.result.ExitCode) } else if _, ok := ytdlp.IsMisconfigError(err); ok { fmt.Println("yt-dlp not installed. Downloading...") ytdlp.MustInstall(ctx, nil) } else if _, ok := ytdlp.IsParsingError(err); ok { fmt.Println("Invalid flags - check version compatibility") } return } ``` -------------------------------- ### Pattern 8: Reusable Command Template Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Defines a reusable command configuration structure (`VideoConfig`) that can be converted into a `go-ytdlp.Command`. This promotes code reuse and simplifies complex download setups. ```go package main import ( "context" "fmt" "github.com/lrstanley/go-ytdlp" ) // VideoConfig represents common download settings type VideoConfig struct { Format string OutputDir string Subtitles bool SubtitleLangs []string WriteMetadata bool } // ToCommand converts VideoConfig to a Command func (c *VideoConfig) ToCommand() *ytdlp.Command { cmd := ytdlp.New(). Format(c.Format). Output(fmt.Sprintf("%s/%%(title)s.%%(ext)s", c.OutputDir)). Continue(). NoOverwrites() if c.Subtitles && len(c.SubtitleLangs) > 0 { for _, lang := range c.SubtitleLangs { cmd = cmd.SubLangs(lang) } cmd = cmd.SubFormat("vtt") } if c.WriteMetadata { cmd = cmd.WriteInfoJSON() } return cmd } func main() { ytdlp.MustInstall(context.Background(), nil) config := &VideoConfig{ Format: "best[ext=mp4]", OutputDir: "downloads", Subtitles: true, SubtitleLangs: []string{"en", "es"}, WriteMetadata: true, } result, err := config.ToCommand(). Run(context.Background(), "https://example.com/video") if err != nil { panic(err) } fmt.Printf("Exit code: %d\n", result.ExitCode) } ``` -------------------------------- ### Error Handling Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/README.md Provides a three-tier error handling approach for command execution, checking for execution errors, execution results, and then processing the results. ```go result, err := cmd.Run(ctx, url) // 1. Check for execution errors if err != nil { if errExit, ok := ytdlp.IsExitCodeError(err); ok { fmt.Printf("yt-dlp exited with code %d\n", errExit.result.ExitCode) } else if _, ok := ytdlp.IsMisconfigError(err); ok { fmt.Println("yt-dlp not found - install it first") ytdlp.MustInstall(ctx, nil) } else if _, ok := ytdlp.IsParsingError(err); ok { fmt.Println("Invalid flags - check version compatibility") } return } // 2. Check execution result if result.ExitCode != 0 { fmt.Printf("Download failed: %s\n", result.Stderr) return } // 3. Process results infos, err := result.GetExtractedInfo() if err != nil { fmt.Println("Failed to parse output:", err) return } ``` -------------------------------- ### SetEnvVar Method Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Sets an environment variable for the yt-dlp command. If value is empty, the variable will be removed. The PATH variable is automatically merged with the parent process's PATH. ```go cmd := ytdlp.New(). SetEnvVar("HOME", "/tmp"). SetEnvVar("LANG", "en_US.UTF-8") ``` -------------------------------- ### SetSeparateProcessGroup Method Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Sets whether the yt-dlp process should run in a separate process group. This prevents signals (like SIGTERM) from being propagated to the parent process. Only supported on Windows and Unix-like systems. ```go cmd := ytdlp.New().SetSeparateProcessGroup(true) ``` -------------------------------- ### Log Progress for Observability Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Demonstrates how to set up a progress function to log download status and progress. ```go cmd.ProgressFunc(time.Second, func(u ytdlp.ProgressUpdate) { log.Printf("[%s] %s: %.0f%% (%d/%d bytes)", u.Status, u.Filename, u.Percent(), u.DownloadedBytes, u.TotalBytes) }) ``` -------------------------------- ### Batch Download from File Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Download multiple videos from a file. ```go package main import ( "context" "github.com/lrstanley/go-ytdlp" ) func main() { ytdlp.MustInstall(context.Background(), nil) _, err := ytdlp.New(). Format("best"). Output("downloads/%(title)s.%(ext)s"). Continue(). IgnoreErrors(). // Skip unavailable videos BatchFile("urls.txt"). Run(context.Background()) if err != nil { panic(err) } } ``` -------------------------------- ### UnsetStderrFunc Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Example of removing a previously set stderr callback function. ```go cmd.UnsetStderrFunc() ``` -------------------------------- ### Best Practice: Use Continue() for Large Downloads Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Resumes incomplete downloads and avoids redownloading. ```go cmd := ytdlp.New(). Continue(). // Resume incomplete downloads NoOverwrites() // Don't redownload ``` -------------------------------- ### IsCompletedType Method Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Provides an example of using the IsCompletedType method to check if a ProgressStatus indicates a completed state (either finished or error). ```go if update.Status.IsCompletedType() { fmt.Printf("Download complete: %s\n", update.Status) } ``` -------------------------------- ### Clone for Concurrent Operations Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Shows how to clone a base command configuration to run multiple operations concurrently. ```go baseCmd := ytdlp.New().Format("best") for _, url := range urls { go func(u string) { cmd := baseCmd.Clone() cmd.Run(ctx, u) }(url) } ``` -------------------------------- ### Progress Callbacks Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/README.md Demonstrates how to use callbacks to track download progress. ```go // ProgressFunc: Structured progress updates (recommended) cmd.ProgressFunc(500*time.Millisecond, func(u ytdlp.ProgressUpdate) { fmt.Printf("[%%s] %%s: %% .0f%% (ETA: %%v)\n", u.Status, u.Filename, u.Percent(), u.ETA()) }) // StderrFunc: Raw stderr output (ffmpeg progress, etc.) cmd.StderrFunc(func(line string) { fmt.Println("[ffmpeg]", line) }) ``` -------------------------------- ### Example Usage of IsJSONParsingFlagError Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Demonstrates how to check for and handle ErrJSONParsingFlag errors. ```go config := &ytdlp.FlagConfig{} // Configure config from JSON... if err := config.Validate(); err != nil { if errFlag, ok := ytdlp.IsJSONParsingFlagError(err); ok { fmt.Printf("Flag validation failed at %s: %s\n", errFlag.JSONPath, errFlag.Flag) } } ``` -------------------------------- ### Simple Download with Format Selection Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Download a single video in a specific format. ```go package main import ( "context" "log" "github.com/lrstanley/go-ytdlp" ) func main() { ytdlp.MustInstall(context.Background(), nil) result, err := ytdlp.New(). Format("bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]"). FormatSort("res,ext:mp4:m4a"). Output("downloads/%(title)s.%(ext)s"). Run(context.Background(), "https://www.youtube.com/watch?v=dQw4w9WgXcQ") if err != nil { log.Fatal(err) } if result.ExitCode != 0 { log.Fatalf("Download failed: %s\n", result.Stderr) } log.Println("Download complete!") } ``` -------------------------------- ### Result Inspection Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/errors.md Shows how to inspect the Result object even when an error is returned. ```go result, err := cmd.Run(ctx, url) if result != nil { fmt.Printf("Exit code: %d\n", result.ExitCode) fmt.Printf("Stderr: %s\n", result.Stderr) } if err != nil { log.Fatal(err) } ``` -------------------------------- ### UnsetProgressFunc Example Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Removes the progress callback function previously set with ProgressFunc. ```go cmd.UnsetProgressFunc() ``` -------------------------------- ### Playlist Download with Progress Tracking Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Download entire playlist with progress updates and resume capability. ```go package main import ( "context" "fmt" "time" "github.com/lrstanley/go-ytdlp" ) func main() { ytdlp.MustInstall(context.Background(), nil) cmd := ytdlp.New(). Format("best[ext=mp4]"). Output("playlists/%(playlist)s/%(playlist_index)02d - %(title)s.%(ext)s"). Continue(). NoOverwrites(). IgnoreErrors(). ProgressFunc(time.Second, trackProgress) result, err := cmd.Run(context.Background(), "https://www.youtube.com/playlist?list=PLxxxxxx") if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } } func trackProgress(update ytdlp.ProgressUpdate) { status := fmt.Sprintf("[%s]", update.Status) percent := fmt.Sprintf("%.1f%%", update.Percent()) eta := fmt.Sprintf("ETA: %v", update.ETA()) fmt.Printf("\r%-15s %-10s %-15s %s ", status, percent, eta, update.Filename) } ``` -------------------------------- ### Handle Both Error and Result Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Demonstrates how to check for both execution errors and yt-dlp specific failures when running a command. ```go result, err := cmd.Run(ctx, url) if err != nil { // Handle execution error fmt.Println("Execution error:", err) } if result != nil && result.ExitCode != 0 { // Handle yt-dlp failure fmt.Println("yt-dlp failed:", result.Stderr) } ``` -------------------------------- ### New Command Constructor Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/command.md Creates a new Command instance with default settings. This is the recommended way to create a new yt-dlp command builder. ```go func New() *Command ``` ```go cmd := ytdlp.New() ``` -------------------------------- ### Multi-Language Subtitles Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Download with subtitles in multiple languages. ```go package main import ( "context" "github.com/lrstanley/go-ytdlp" ) func main() { ytdlp.MustInstall(context.Background(), nil) _, err := ytdlp.New(). Format("best[ext=mp4]"). AllSubtitle(). SubLangs("en,es,fr,de,ja"). SubFormat("vtt"). EmbedSubtitle(). Output("videos/%(title)s.%(ext)s"). Run(context.Background(), "https://example.com/video") if err != nil { panic(err) } } ``` -------------------------------- ### Pattern 12: Cloning for Concurrent Downloads Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Demonstrates downloading multiple URLs concurrently by cloning the base command for each download. ```go package main import ( "context" "sync" "github.com/lrstanley/go-ytdlp" ) func main() { ytdlp.MustInstall(context.Background(), nil) baseCmd := ytdlp.New(). Format("best[ext=mp4]"). Output("downloads/%(title)s.%(ext)s"). Continue() urls := []string{ "https://example.com/video1", "https://example.com/video2", "https://example.com/video3", } var wg sync.WaitGroup for _, url := range urls { wg.Add(1) go func(u string) { defer wg.Done() // Clone to create independent command cmd := baseCmd.Clone() result, _ := cmd.Run(context.Background(), u) if result != nil && result.ExitCode == 0 { println("Downloaded:", u) } }(url) } wg.Wait() } ``` -------------------------------- ### Command Builder Pattern Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/README.md Illustrates the command builder pattern for configuring and executing yt-dlp commands. ```go cmd := ytdlp.New(). Format("best[ext=mp4]"). FormatSort("res,ext:mp4:m4a"). Output("% (title)s.%(ext)s"). NoOverwrites(). Continue(). ProgressFunc(time.Second, func(u ytdlp.ProgressUpdate) { fmt.Printf("%%.0f%%\n", u.Percent()) }) result, err := cmd.Run(ctx, "https://example.com/video") ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/README.md Illustrates how to configure the yt-dlp execution environment using environment variables, setting working directory, proxy, and cancelation timeout. ```go cmd := ytdlp.New(). SetWorkDir("/tmp/downloads"). SetEnvVar("HOME", "/tmp"). SetEnvVar("http_proxy", "http://proxy:8080"). SetEnvVarInherit(true). // Inherit parent environment SetCancelMaxWait(5 * time.Second) ``` -------------------------------- ### Basic Usage Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/README.md Demonstrates the basic usage of the go-ytdlp library to download a video. ```go package main import ( "context" "github.com/lrstanley/go-ytdlp" ) func main() { // Ensure yt-dlp is installed ytdlp.MustInstall(context.Background(), nil) // Create and execute command result, err := ytdlp.New(). Format("best"). Output("% (title)s.%(ext)s"). Run(context.Background(), "https://www.youtube.com/watch?v=dQw4w9WgXcQ") if err != nil { panic(err) } } ``` -------------------------------- ### ProgressStatus Constants Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/api-reference/results.md Defines the ProgressStatus enumeration, which represents the different stages of a download process, including starting, downloading, post-processing, error, and finished states. ```go type ProgressStatus string const ( ProgressStatusStarting ProgressStatus = "starting" ProgressStatusDownloading ProgressStatus = "downloading" ProgressStatusPostProcessing ProgressStatus = "post_processing" ProgressStatusError ProgressStatus = "error" ProgressStatusFinished ProgressStatus = "finished" ) ``` -------------------------------- ### Pattern 7: Video with Metadata Files Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/PATTERNS.md Downloads a video with its associated metadata (info.json), thumbnails, and subtitles. This pattern is useful for archiving content with all relevant details. ```go package main import ( "context" "github.com/lrstanley/go-ytdlp" ) func main() { ytdlp.MustInstall(context.Background(), nil) _, err := ytdlp.New(). Format("best[ext=mp4]"). WriteThumbnail(). ConvertThumbnails("jpg"). WriteInfoJSON(). WriteSubtitle(). SubFormat("srt"). Output("videos/%(title)s.%(ext)s"). Run(context.Background(), "https://example.com/video") if err != nil { panic(err) } } ``` -------------------------------- ### JSON Flag Configuration Source: https://github.com/lrstanley/go-ytdlp/blob/master/_autodocs/README.md Shows how to load, validate, and save flag configurations as JSON, as well as programmatically create a FlagConfig object. ```go // Load from JSON var config ytdlp.FlagConfig json.Unmarshal(jsonData, &config) // Validate if err := config.Validate(); err != nil { // Handle validation error } // Use cmd := ytdlp.New().SetFlagConfig(&config) // Save to JSON encoded, _ := json.Marshal(config) // Programmatic creation config := &ytdlp.FlagConfig{ VideoFormat: ytdlp.FlagsVideoFormat{ Format: ptr("best[ext=mp4]"), }, Download: ytdlp.FlagsDownload{ NoOverwrites: ptr(true), }, } ```