goutubedl

repository·master·Indexed 41 days ago

https://github.com/wader/goutubedl

A Go wrapper for youtube-dl and yt-dlp command-line tools that provides a programmatic API and CLI to download videos and media from various platforms. It includes functionality for metadata extraction via the Info struct, format filtering, authentication via .netrc, and support for playlists, channels, and proxy configurations.

Tokens
2.6K
Snippets
10
Records
13
Agent score
52%

What's inside goutubedl

  1. Install and use goutubedl

    master

    goutubedl is a Go wrapper for youtube-dl and yt-dlp. It is currently tested and developed primarily using yt-dlp.

    To use this library, you must have yt-dlp (preferred) or youtube-dl installed on your system and available in your PATH. You can also explicitly configure the binary location using the goutubedl.Path variable.

    For installation instructions and recommended additional dependencies, refer to the official yt-dlp documentation.

    go get github.com/wader/goutubedl
  2. Understand the Info structure

    master

    The Info struct contains comprehensive metadata about the media, mapped from the youtube-dl JSON output.

    Key sections include:

    • Basic Info: ID, Title, URL, Uploader, Duration, ViewCount.
    • Formats: A slice of Format objects describing available streams (resolution, bitrate, codec, etc.). Use the Formats() helper method on a Result to get a flattened list.
    • Thumbnails: A slice of Thumbnail objects. If DownloadThumbnail was enabled in Options, ThumbnailBytes will be populated.
    • Subtitles: A map of languages to Subtitle slices. If DownloadSubtitles was enabled, Bytes will be populated.
    • Playlist/Series Info: Fields like PlaylistID, Series, Season, Episode, etc., are available depending on the content type.
  3. Authentication and Cache configuration

    master

    Authentication

    goutubedl uses the --netrc flag by default, which allows it to use authentication data stored in your ~/.netrc file.

    Cache Directory

    yt-dlp stores extractor session data in ${XDG_CACHE_HOME}/yt-dlp (typically ~/.cache/yt-dlp). If you are running goutubedl in ephemeral environments like containers, you may want to persist this directory to improve performance and speed up extraction processes.

  4. Set the youtube-dl/yt-dlp binary path

    master

    By default, goutubedl looks for youtube-dl then yt-dlp in your system PATH. You can override this by setting the goutubedl.Path variable. You can also use ProbePath() to check which binary is currently being used.

    // Manually specify the path to yt-dlp
    goutubedl.Path = "/usr/local/bin/yt-dlp"
    
    // Or check what was found
    path, _ := goutubedl.ProbePath()
    fmt.Println("Using binary at:", path)
  5. Download a video using goutubedl

    master

    To download a video, use goutubedl.New to create a result object, then call .Download on that object. The .Download method requires a context and a format string (e.g., "best"). The returned downloadResult implements io.ReadCloser, which you should close after use.

    Example usage:

    package main
    
    import (
    	"context"
    	"io"
    	"log"
    	"os"
    
    	"github.com/wader/goutubedl"
    )
    
    func main() {
    	// Initialize the downloader
    	result, err := goutubedl.New(context.Background(), "https://www.youtube.com/watch?v=jgVhBThJdXc", goutubedl.Options{})
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Download the video with the specified format (e.g., "best")
    	downloadResult, err := result.Download(context.Background(), "best")
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer downloadResult.Close()
    
    	// Save the output to a file
    	f, err := os.Create("output")
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer f.Close()
    
    	// Stream the download to the file
    	io.Copy(f, downloadResult)
    }
    package main
    
    import (
    	"context"
    	"io"
    	"log"
    	"os"
    
    	"github.com/wader/goutubedl"
    )
    
    func main() {
    	result, err := goutubedl.New(context.Background(), "https://www.youtube.com/watch?v=jgVhBThJdXc", goutubedl.Options{})
    	if err != nil {
    		log.Fatal(err)
    	}
    	downloadResult, err := result.Download(context.Background(), "best")
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer downloadResult.Close()
    	f, err := os.Create("output")
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer f.Close()
    	io.Copy(f, downloadResult)
    }
  6. Configure goutubedl Options

    master

    The Options struct controls how youtube-dl/yt-dlp behaves during the metadata extraction phase. Key fields include:

    • Type: Set to TypeSingle, TypePlaylist, TypeChannel, or TypeAny to control playlist handling.
    • ProxyUrl: A URL for proxying (e.g., http://host:port or socks5://host:port).
    • Cookies: Path to a cookies file.
    • CookiesFromBrowser: Browser name and optional folder (e.g., chrome[:folder]).
    • DownloadThumbnail: If true, downloads the thumbnail bytes into Info.ThumbnailBytes.
    • DownloadSubtitles: If true, downloads subtitle bytes into Info.Subtitles.
    • UseIPV4: Forces IPv4 connections.
    • DebugLog: An implementation of the Printer interface to capture logs.
    opts := goutubedl.Options{
        Type:              goutubedl.TypePlaylist,
        PlaylistStart:     1,
        PlaylistEnd:       5,
        DownloadThumbnail: true,
        UseIPV4:           true,
        ProxyUrl:          "http://localhost:8080",
    }
  7. Configure DownloadOptions

    master

    The DownloadOptions struct controls the actual media extraction/downloading phase. Key fields include:

    • Filter: A string representing the format selection (e.g., "bestaudio").
    • DownloadAudioOnly: If true, uses the -x flag to extract audio.
    • AudioFormats: A string of formats to use (e.g., "mp3,m4a,opus").
    • PlaylistIndex: The index of the entry to download from a playlist (starts at 1).
    downloadOpts := goutubedl.DownloadOptions{
        DownloadAudioOnly: true,
        AudioFormats:      "mp3",
        PlaylistIndex:     2,
    }
  8. Initialize goutubedl with New()

    master

    Use New(ctx, rawURL, options) to fetch metadata for a given URL. This returns a Result object containing the Info (metadata), the raw JSON response, and the original options. This is the standard way to inspect a video's properties (title, duration, formats, etc.) before deciding how to download it.

    result, err := goutubedl.New(ctx, "https://www.youtube.com/watch?v=...", goutubedl.Options{
        Type: goutubedl.TypeSingle,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Title:", result.Info.Title)
  9. Download media with Download()

    master

    The Download(ctx, rawURL, options, filter) function is a convenience method that performs both metadata extraction and downloading in a single pass. It is more efficient if you do not need to inspect the Info structure before starting the download. The filter parameter allows you to specify a format ID or quality designator (e.g., "bestvideo+bestaudio/best").

    // Downloads the video using the default format selector
    dr, err := goutubedl.Download(ctx, "https://www.youtube.com/watch?v=...", goutubedl.Options{}, "")
    if err != nil {
        log.Fatal(err)
    }
    defer dr.Close()
    
    // Stream the download to stdout or a file
    _, err = io.Copy(os.Stdout, dr)
  10. Handle DownloadResult streams

    master

    The DownloadResult returned by Download methods implements io.ReadCloser. You can read the downloaded media directly from it. It is critical to call dr.Close() to ensure the underlying youtube-dl process is waited on and temporary files are cleaned up.

    dr, err := result.Download(ctx, "")
    if err != nil {
        return err
    }
    // Ensure cleanup
    defer dr.Close()
    
    // Read the stream
    _, err = io.Copy(destinationFile, dr)
  11. Download from a Result using Download() or DownloadWithOptions()

    master

    If you have already called New() and have a Result object, you can trigger the download using result.Download(ctx, filter) or result.DownloadWithOptions(ctx, options).

    Note: If you are downloading a playlist, you must set the PlaylistIndex in DownloadOptions to specify which item to download.

    // Using a previously obtained Result
    dr, err := result.Download(ctx, "best")
    if err != nil {
        log.Fatal(err)
    }
    defer dr.Close()
    
    // Or with specific download options
    dr, err = result.DownloadWithOptions(ctx, goutubedl.DownloadOptions{
        AudioFormats:      "mp3",
        DownloadAudioOnly: true,
        PlaylistIndex:     1, // Required for playlists
    })
  12. Error types in goutubedl

    master

    The package defines specific error types and variables to help distinguish between different failure modes:

    • YoutubedlError: A string-based error type that carries the exact error message returned by the youtube-dl stderr.
    • ErrNotAPlaylist: Returned when TypeSingle was requested but a playlist was found.
    • ErrNotASingleEntry: Returned when TypePlaylist was requested but only a single entry was found.