ytsr

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 5, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

README

ytsr

Minimal and fast YouTube search library for Go.

Install

go get github.com/nixietab/ytsr

Usage

package main

import (
	"context"
	"fmt"

	"github.com/nixietab/ytsr"
)

func main() {
	ctx := context.Background()
	client := ytsr.New()

	video, err := client.First(ctx, "never gonna give you up")
	if err != nil {
		panic(err)
	}
	fmt.Println(video.Title, video.ID, video.URL, video.Thumbnail)

	videos, err := client.Search(ctx, "lofi beats", 5)
	if err != nil {
		panic(err)
	}
	for _, v := range videos {
		fmt.Println(v.Title)
	}
}

API

  • ytsr.New(opts ...Option) *Client - create a client; options: WithHTTPClient, WithUserAgent, WithLanguage, WithRegion
  • (*Client).Search(ctx, query string, limit int) ([]Video, error) - top results for a query
  • (*Client).First(ctx, query string) (Video, error) - top result only
  • ytsr.GetByID(id string) (Video, error) - build a Video from an ID
  • ytsr.ExtractVideoID(u string) (string, error) - extract an ID from a YouTube URL
Video
Field Description
ID YouTube video ID
Title Video title
URL Canonical watch?v= URL
Thumbnail Largest thumbnail URL from the page

Errors

Search failures return sentinel errors where applicable: ytsr.ErrNoResults and ytsr.ErrParse.

Note

  • Scraping relies on YouTube's HTML structure (ytInitialData) and may break if YouTube changes it.

License

GNU Affero General Public License v3.0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoResults = errors.New("ytsr: no results found")
	ErrParse     = errors.New("ytsr: failed to parse search page")
)

Functions

func ExtractVideoID

func ExtractVideoID(u string) (string, error)

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Client

func (*Client) First

func (c *Client) First(ctx context.Context, query string) (Video, error)

func (*Client) Search

func (c *Client) Search(ctx context.Context, query string, limit int) ([]Video, error)

type Option

type Option func(*Client)

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

func WithLanguage

func WithLanguage(hl string) Option

func WithRegion

func WithRegion(gl string) Option

func WithUserAgent

func WithUserAgent(ua string) Option

type Video

type Video struct {
	ID        string        `json:"id"`
	Title     string        `json:"title"`
	URL       string        `json:"url"`
	Thumbnail string        `json:"thumbnail"`
	Duration  time.Duration `json:"duration"`
}

func GetByID

func GetByID(videoID string) (Video, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL