ddgs

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 32 Imported by: 0

README

ddgs-go | Dux Distributed Global Search (Go)

A Go port of the Python ddgs library — a metasearch library that aggregates results from diverse web search services, with an API that mirrors the Python version.

Install

go get github.com/dreamyang-liu/ddgs-go

Quick start

package main

import (
	"context"
	"fmt"

	ddgs "github.com/dreamyang-liu/ddgs-go"
)

func main() {
	d, err := ddgs.New(nil) // defaults: 5s timeout, no proxy, TLS verify on
	if err != nil {
		panic(err)
	}
	results, err := d.Text(context.Background(), "golang concurrency", nil)
	if err != nil {
		panic(err)
	}
	for _, r := range results {
		fmt.Println(r["title"], r["href"])
	}
}

API mapping (Python → Go)

Python Go
DDGS(proxy=..., timeout=..., verify=...) ddgs.New(&ddgs.Config{Proxy, Timeout, Verify, Threads})
ddgs.text(query, ...) d.Text(ctx, query, opts)
ddgs.images(query, ...) d.Images(ctx, query, opts)
ddgs.news(query, ...) d.News(ctx, query, opts)
ddgs.videos(query, ...) d.Videos(ctx, query, opts)
ddgs.books(query, ...) d.Books(ctx, query, opts)
ddgs.extract(url, fmt) d.Extract(ctx, url, format)
region="us-en" opts.Region (default "us-en")
safesearch="moderate" opts.SafeSearch (default "moderate")
timelimit="d"/"w"/"m"/"y" opts.TimeLimit
max_results=10 opts.MaxResults (default 10; -1 = unlimited, like None)
page=1 opts.Page
backend="auto" opts.Backend (comma-delimited, default "auto")
**kwargs (size, color, resolution, …) opts.Extra map[string]string
DDGS_PROXY env var DDGS_PROXY env var (same)
proxy="tb" Tor alias Proxy: "tb" (same)
DDGSException / TimeoutException ddgs.ErrDDGS / ddgs.ErrTimeout (errors.Is)

Results are returned as []ddgs.Result where Result is map[string]any with the same keys as the Python dicts (title, href, body for text; date, title, body, url, image, source for news; etc.).

Engines

Function Available backends
Text brave, duckduckgo, google, grokipedia, mojeek, startpage, wikipedia, yahoo, yandex
Images bing, duckduckgo
News bing, duckduckgo, yahoo
Videos duckduckgo
Books annasarchive

Result semantics match the Python implementation: with backend: "auto" engines are shuffled, wikipedia/grokipedia are prioritized for text search, one request is issued per unique provider, results are deduplicated by URL, counted across engines, and ranked (wikipedia first, then title+body match, title-only, body-only, neither). Behavior is verified against Python ddgs v9.14.4 by golden-vector parity tests (testdata/).

The scheduler improves on the Python thread-pool waves:

  • Streaming fan-out — results are consumed as each engine finishes; once MaxResults is reached, in-flight requests are cancelled instead of waiting on the slowest engine.
  • General-engine floor — at least one general SERP engine is in flight from the start, alongside the single-result encyclopedia engines.
  • Failure cooldown — engines that fail repeatedly (e.g. IP-blocked) are skipped in auto mode for 5 minutes. In-memory, per DDGS instance; reuse one instance to benefit. Explicit Backend selection bypasses it.

Examples

ctx := context.Background()

// Specific backends, news from the last week
news, err := d.News(ctx, "AI", &ddgs.SearchOptions{
	Backend:    "duckduckgo,yahoo",
	TimeLimit:  "w",
	MaxResults: 20,
})

// Image search with filters (same kwargs as Python)
imgs, err := d.Images(ctx, "sunset", &ddgs.SearchOptions{
	Extra: map[string]string{"size": "Large", "color": "Monochrome"},
})

// Behind a proxy
d, err := ddgs.New(&ddgs.Config{Proxy: "socks5://127.0.0.1:9150"})

// Extract page content as Markdown
page, err := d.Extract(ctx, "https://example.com", ddgs.FormatTextMarkdown)
fmt.Println(page.Content)

Differences from the Python version

  • Methods take a context.Context and return error (Go idiom) instead of raising exceptions.
  • max_results=None is expressed as MaxResults: -1.
  • HTTP requests use net/http with browser-like headers instead of primp's TLS impersonation, so heavily-fingerprinting engines may rate-limit sooner.
  • Extract's markdown conversion uses html-to-markdown (links, emphasis and tables preserved as standard CommonMark) rather than primp's Rust converter; output is richer but not byte-identical.
  • The auto-mode scheduler streams results and cancels early (see Engines); the Python version waits on thread-pool waves.
  • The CLI / API server / MCP server of the Python package are out of scope; this is the library only.

Disclaimer

Same as upstream: this library is for educational purposes; you are responsible for complying with the terms of service of the search engines it talks to.

Documentation

Overview

Package ddgs is a Go port of the Python "ddgs" library (https://github.com/deedy5/ddgs) — DDGS | Dux Distributed Global Search. A metasearch library that aggregates results from diverse web search services.

Index

Constants

View Source
const DefaultMaxResults = 10

DefaultMaxResults mirrors the Python default max_results=10.

Variables

View Source
var ErrDDGS = errors.New("ddgs")

ErrDDGS is the base error for the ddgs package. All errors returned by this package wrap ErrDDGS.

View Source
var ErrNoResults = errors.New("ddgs: no results found")

ErrNoResults is returned when no engine produced any results.

View Source
var ErrRatelimit = errors.New("ddgs: ratelimit")

ErrRatelimit is returned for rate limit exceeded errors during requests.

View Source
var ErrTimeout = errors.New("ddgs: timeout")

ErrTimeout is returned for timeout errors during requests.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Proxy for the HTTP clients; supports http/https/socks5 URLs.
	// The alias "tb" expands to the Tor Browser proxy. Falls back to the
	// DDGS_PROXY environment variable when empty.
	Proxy string
	// Timeout per engine request. Defaults to 5s (Python default timeout=5).
	Timeout time.Duration
	// Verify controls TLS verification.
	Verify Verify
	// Threads caps the number of concurrent engine requests per search.
	// Zero means automatic (based on max_results), mirroring DDGS.threads.
	Threads int
}

Config configures a DDGS instance, mirroring DDGS.__init__ kwargs.

type DDGS

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

DDGS | Dux Distributed Global Search. A metasearch client that aggregates results from diverse web search services.

d, err := ddgs.New(nil)
results, err := d.Text(ctx, "python", nil)

DDGS is safe for concurrent use: the engine cache is mutex-protected and engines only mutate goroutine-safe state (net/http cookie jars) after construction.

func New

func New(cfg *Config) (*DDGS, error)

New creates a DDGS instance. A nil config uses defaults (no proxy — or DDGS_PROXY env var, 5s timeout, TLS verification on).

func (*DDGS) Books

func (d *DDGS) Books(ctx context.Context, query string, opts *SearchOptions) ([]Result, error)

Books performs a book search. Mirrors DDGS.books().

func (*DDGS) Extract

func (d *DDGS) Extract(ctx context.Context, rawURL string, format ExtractFormat) (*Extracted, error)

Extract fetches a URL and extracts its content. Mirrors DDGS.extract().

func (*DDGS) Images

func (d *DDGS) Images(ctx context.Context, query string, opts *SearchOptions) ([]Result, error)

Images performs an image search. Mirrors DDGS.images().

func (*DDGS) News

func (d *DDGS) News(ctx context.Context, query string, opts *SearchOptions) ([]Result, error)

News performs a news search. Mirrors DDGS.news().

func (*DDGS) Text

func (d *DDGS) Text(ctx context.Context, query string, opts *SearchOptions) ([]Result, error)

Text performs a text search. Mirrors DDGS.text().

func (*DDGS) Videos

func (d *DDGS) Videos(ctx context.Context, query string, opts *SearchOptions) ([]Result, error)

Videos performs a video search. Mirrors DDGS.videos().

type ExtractFormat

type ExtractFormat string

ExtractFormat selects the output format of Extract, mirroring the Python `fmt` parameter values.

const (
	// FormatTextMarkdown converts the page to Markdown-ish plain text (default).
	FormatTextMarkdown ExtractFormat = "text_markdown"
	// FormatTextPlain converts the page to plain text.
	FormatTextPlain ExtractFormat = "text_plain"
	// FormatText returns the raw HTML text.
	FormatText ExtractFormat = "text"
	// FormatContent returns the raw response bytes.
	FormatContent ExtractFormat = "content"
)

type Extracted

type Extracted struct {
	URL     string
	Content string // textual formats
	Bytes   []byte // FormatContent
}

Extracted is the return value of Extract, mirroring the Python {"url": ..., "content": ...} dict.

type Result

type Result map[string]any

Result is a single search result. It mirrors the dicts returned by the Python ddgs library: keys and value shapes are identical per category.

text:   title, href, body
images: title, image, thumbnail, url, height, width, source
news:   date, title, body, url, image, source
videos: title, content, description, duration, embed_html, embed_url,
        image_token, images, provider, published, publisher, statistics, uploader
books:  title, author, publisher, info, url, thumbnail

func (Result) Set

func (r Result) Set(field string, value any)

Set assigns a value to a field, applying the same normalization the Python BaseResult.__setattr__ performs. A nil value is stored as nil (Python stores None), overriding the "" default.

type SearchOptions

type SearchOptions struct {
	// Region, e.g. "us-en", "uk-en", "ru-ru". Default "us-en".
	Region string
	// SafeSearch: "on", "moderate", "off". Default "moderate".
	SafeSearch string
	// TimeLimit: "d", "w", "m", "y". Default none.
	TimeLimit string
	// MaxResults is the maximum number of results to return. Default 10.
	// Set to -1 to return everything found (Python max_results=None).
	MaxResults int
	// Page of results, 1-based. Default 1.
	Page int
	// Backend is a single or comma-delimited list of backends, or
	// "auto"/"all". Default "auto".
	Backend string
	// Extra engine-specific parameters, mirroring Python **kwargs
	// (e.g. images: size, color, type_image, layout, license_image;
	// videos: resolution, duration, license_videos).
	Extra map[string]string
}

SearchOptions are the per-search keyword arguments, mirroring DDGS._search_sync kwargs. The zero value gives Python's defaults.

type Verify

type Verify struct {
	// SkipVerify disables TLS certificate verification (Python verify=False).
	SkipVerify bool
	// CACertFile is a path to a PEM file with custom CA certs (Python verify="path").
	CACertFile string
}

Verify controls TLS verification, mirroring the Python `verify: bool | str` parameter (True / False / path-to-PEM).

Jump to

Keyboard shortcuts

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