retrieval-go
A fast, batteries-included web retrieval library for Go.
retrieval-go is a production-oriented DuckDuckGo HTML search client + Bing image search + web page content extractor designed for building LLM tools (RAG, agents, “browse the web” features) without relying on paid search APIs.
It provides:
- Search (
query -> []Page) using DuckDuckGo’s Lite HTML endpoint.
- Image search (
query -> []Image) using Bing, with relevance filtering.
- Content extraction (
url -> Document) powered by go-readability.
- Robust defaults (headers, TLS fingerprint impersonation, decompression, timeouts).
- A configurable
Config API plus ergonomic Option helpers.
Why
Most LLM applications need three things from “internet access”:
- Discover relevant URLs for a query.
- Fetch & extract clean, readable text.
- Keep it reliable (timeouts, gzip/br/zstd, sane defaults).
retrieval-go is built specifically for that workflow.
Features
- DuckDuckGo Lite HTML search (works without browser automation)
- Bing image search with query-relevance scoring and market control (see Market)
- Clean text extraction:
- Returns Markdown (including tables!)
- Filters clutter (ads, nav bars)
- Basic image filtering (removes common icons, logos, flags, and tiny elements)
- Automatic decompression (
gzip, br, zstd, deflate)
- Production defaults
- Chrome TLS fingerprint impersonation, request headers close to a real browser
- optional browser-profile rotation (
WithBrowserRotation)
- proxy support, including a per-request proxy factory
- error-body capture with size limit
- Extensible parsing via the
SearchParser and ImageParser interfaces
- Two configuration styles
New(opts...) (simple)
NewWithConfig(cfg) (explicit)
Install
go get github.com/free-llms-foundation/retrieval-go
Quick start
1) Search
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/free-llms-foundation/retrieval-go"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
c, err := retrieval.New()
if err != nil {
log.Fatal(err)
}
// Second argument is the search query
// Third argument is the date filter (e.g., "d" for day, "w" for week, "m" for month, "y" for year, or "" for all time)
pages, err := c.SearchWithQuery(ctx, "golang generics site:golang.org", "")
if err != nil {
log.Fatal(err)
}
for i, p := range pages {
if i >= 5 {
break
}
fmt.Println("Link:", p.Link)
fmt.Println("Title:", p.Title)
fmt.Println("Snippet:", p.Snippet)
fmt.Println("Favicon:", p.Favicon)
fmt.Print("-------------------------------------------------\n\n")
}
}
func main() {
c, _ := retrieval.New()
ctx := context.Background()
// Third argument is robotsTxtAllowed (bool)
doc, err := c.ParseContentFromLink(ctx, "https://go.dev/blog/generics-next-step", true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Title: %s\n", doc.Title)
fmt.Printf("Site: %s (%s)\n", doc.SiteName, doc.Language)
fmt.Println("---")
fmt.Println(doc.Content) // Clean Markdown
if len(doc.Images) > 0 {
fmt.Printf("\nExtracted %d images (filtered)\n", len(doc.Images))
}
}
3) Image search
func main() {
c, _ := retrieval.New()
ctx := context.Background()
// Same signature as SearchWithQuery: query, then date filter ("d"/"w"/"m"/"y"/"").
images, err := c.SearchImagesWithQuery(ctx, "golden retriever puppy", "")
if err != nil {
if errors.Is(err, retrieval.ErrNoRelevantImages) {
// Bing answered, but nothing it returned matched the query.
return
}
log.Fatal(err)
}
for _, img := range images {
fmt.Println(img.Desc, img.URL)
}
}
Results come back sorted by relevance, most relevant first.
Examples
See the examples/ folder:
examples/search — search only
examples/fetch — fetch + readability extraction for a single URL
examples/images — image search
examples/research — search → fetch multiple pages → print extracted text
Data model
Page
type Page struct {
Link string
Title string
Source string // Hostname or source name
Snippet string // Brief summary from search results
Favicon string // URL to the site's favicon
}
Image
type Image struct {
URL string // Full-size image URL
Thumbnail string // Bing-hosted thumbnail
PageURL string // Page the image was found on
Desc string // Image title / description
}
Document
type Document struct {
Title string
Byline string
Content string // Main content in Markdown
TextContent string // Raw plain text
Excerpt string // Short summary/teaser
SiteName string
Image string // Lead image URL
Images []string // List of article images (smart-filtered)
Favicon string // Source favicon URL
Language string // Detected language code
Length int // Content length in characters
}
Configuration
You can configure the client via Options or via an explicit Config. Both routes
go through the same defaults: New(opts...) starts from DefaultConfig() and applies
the options, NewWithConfig(cfg) takes the struct as-is and fills in any zero field
that has a default.
Options
c, err := retrieval.New(
retrieval.WithTimeout(15*time.Second),
retrieval.WithProxy("http://user:pass@host:port"),
retrieval.WithMaxErrBodyBytes(64*1024),
retrieval.WithMaxBodyBytes(1024*1024),
retrieval.WithBrowserRotation(), // Rotate TLS/browser profiles per request
)
The full set:
| Option |
Config field |
Default |
What it does |
WithClient(HTTPClient) |
HTTPClient |
built-in TLS adapter |
Replaces the whole HTTP layer (see Custom HTTP client) |
WithTimeout(d) |
Timeout |
30s |
Client-wide request timeout |
WithBaseURL(u) |
BaseURL |
https://lite.duckduckgo.com/lite/ |
Search endpoint |
WithCustomImagesURL(u) |
ImagesURL |
https://www.bing.com/images/search |
Image search endpoint |
WithMarket(m) |
Market |
en-US |
Bing mkt parameter (see Market) |
WithSearchParser(p) |
SearchParser |
&DefaultDDGParser{} |
Search HTML parser |
WithImageParser(p) |
ImageParser |
&BingImagesParser{} |
Image HTML parser |
WithImageValidator(v) |
ImageValidator |
trigram Sørensen–Dice |
Relevance metric for image results |
WithImageMinScore(f) |
ImageMinScore |
0.15 |
Cutoff for that metric; out-of-range values fall back to the default |
WithMaxBodyBytes(n) |
MaxBodyBytes |
1 MiB |
Cap on a successful response body |
WithMaxErrBodyBytes(n) |
MaxErrBodyBytes |
64 KiB |
Cap on the error body kept in ErrUnexpectedStatusCode |
WithProxy(u) |
Proxy |
none |
Static proxy (http, https, socks5) |
WithProxyFactory(fn) |
ProxyFactory |
none |
Per-request proxy URL; takes precedence over Proxy |
WithBrowserRotation() |
EnableBrowserRotation |
false |
Pick a random browser/TLS profile per request |
WithMaxIdleConnsPerHost(n) |
MaxIdleConnsPerHost |
32 |
Connection pool size per host |
WithDisableKeepAlive() |
DisableKeepAlive |
false |
Close connections after each request |
WithCommonRetryCount(n) |
CommonRetryCount |
0 |
Transport-level retries |
WithEnableForceHTTP1() |
EnableForceHTTP1 |
false |
Force HTTP/1.1 instead of negotiating h2 |
WithEnableDumpAll() |
EnableDumpAll |
false |
Dump full requests/responses — debugging only |
Options that touch the transport (proxy, keep-alive, pool size, retries, HTTP/1.1,
dumping, rotation) only apply to the built-in client. If you supply your own via
WithClient, they are ignored.
Config
cfg := retrieval.DefaultConfig()
cfg.Timeout = 15 * time.Second
cfg.MaxErrBodyBytes = 64 * 1024
cfg.MaxBodyBytes = 1024 * 1024
cfg.Proxy = "http://localhost:8080"
c, err := retrieval.NewWithConfig(cfg)
Date filters and safe search
Both search calls take the same third argument, a date filter, but the two backends
treat it differently.
SearchWithQuery passes the value straight through as DuckDuckGo's df parameter:
"d", "w", "m", "y", or "" for all time (DDG also accepts date ranges there).
SearchImagesWithQuery maps the value onto Bing's qft=filterui:age-lt… filter and
only understands "d", "w", "m" and "y". Anything else — including a typo — is
silently ignored and you get unfiltered results rather than an error.
Image search always sends adlt=strict, so Bing's safe search is on and there is no
option to turn it off.
Market
Image search sends Bing a market (mkt), defaulting to en-US:
c, err := retrieval.New(
retrieval.WithMarket("en-GB"),
)
This is not a cosmetic setting. Without mkt, Bing answers a large share of image
queries with a result set for something else entirely. Measured as a paired A/B over
30 queries, a fresh client per request and the order swapped per query:
|
usable results |
nothing relevant |
| no market |
11/30 |
19/30 |
mkt=en-US |
22/30 |
8/30 |
The queries where the two variants disagreed are the ones carrying the evidence:
13 worked only with the market, 2 only without it. setlang makes no difference;
cc behaves like mkt.
Set the market, but do not expect it to be a cure — roughly a quarter of queries
still come back substituted. Non-English queries are the known weak spot: Cyrillic,
Japanese and German queries returned unrelated results under every market tried,
including a matching one, and en-US neither fixed nor worsened them.
WithMarket("") omits the parameter entirely and restores the old behaviour.
Image relevance filtering
Bing's image results are not always about what you asked for, so every result is
scored against the query and low scorers are dropped. The score is the best match
across three signals: the image title, the source page URL slug, and the image URL
slug.
The defaults are trigram Sørensen–Dice with a cutoff of 0.15. Both are tunable:
c, err := retrieval.New(
retrieval.WithImageValidator(&metrics.SorensenDice{CaseSensitive: false, NgramSize: 2}),
retrieval.WithImageMinScore(0.25),
)
ImageValidator is a one-method interface (Compare(a, b string) float64), so any
metric from adrg/strutil satisfies it as-is, as
does anything you write yourself. WithImageMinScore(0) keeps everything the parser
produced.
A note on the cutoff: trigram Dice scores are low in absolute terms, and they fall as
the query gets longer. 0.15 sits just above the noise floor rather than at an
intuitive-looking 0.4 — an aggressive threshold discards genuinely relevant results
for multi-word queries. If you raise it, re-check recall on your own long queries.
If nothing clears the cutoff, SearchImagesWithQuery returns ErrNoRelevantImages
rather than an empty slice, so a filtered-to-nothing response is distinguishable from
a successful empty one.
Proxy Support
You can easily route requests through a proxy (http, https, socks5) using WithProxy:
c, err := retrieval.New(
retrieval.WithProxy("http://user:pass@127.0.0.1:8080"),
)
Custom HTTP client
If you need a custom transport (mTLS, custom DNS, etc.) that goes beyond simple
proxying, supply your own client. WithClient takes an interface, not a concrete
type:
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
*http.Client satisfies it, so the common case is a one-liner:
hc := &http.Client{ /* custom Transport, etc. */ }
c, err := retrieval.New(
retrieval.WithClient(hc),
// Optional: override timeout as well
retrieval.WithTimeout(10*time.Second),
)
Doing this replaces the TLS-impersonation layer, so the browser fingerprint,
rotation, proxy and keep-alive settings no longer apply — your client is fully
responsible for how requests hit the wire. If you want to keep impersonation and
only wrap it, build the default adapter yourself with retrieval.NewTLSAdapter.
Parser customization
Parsing is abstracted behind two interfaces:
type SearchParser interface {
Parse(reader io.ReadCloser) ([]Page, error)
}
type ImageParser interface {
Parse(reader io.ReadCloser) ([]Image, error)
}
Supply your own if an upstream changes its markup, or if you want to target another HTML endpoint:
c, err := retrieval.New(
retrieval.WithSearchParser(mySearchParser{}),
retrieval.WithImageParser(myImageParser{}),
retrieval.WithBaseURL("https://example.invalid/lite/"),
retrieval.WithCustomImagesURL("https://example.invalid/images/search"),
)
The built-in implementations are exported, so you can embed or fall back to them:
retrieval.DefaultDDGParser for search and retrieval.BingImagesParser for images.
Both receive an already-decompressed, size-limited reader (MaxBodyBytes), so a
parser never has to deal with Content-Encoding itself.
Testing
go test ./... # unit tests, parsers run against testdata/ fixtures
go test -race ./... # what CI runs
go test -tags=integration ./... # hits DuckDuckGo and Bing over the network
Parser tests are fixture-driven; the fixtures in testdata/ are captured HTML from the
real endpoints. To refresh them after an upstream markup change, run from the repo root:
go run ./cmd/capture_fixtures/
Error handling
When DuckDuckGo (or a target site) returns a non-2xx response, retrieval-go returns an error wrapping:
retrieval.ErrUnexpectedStatusCode
When a target page is disallowed by robots.txt (and robots enforcement is enabled), ParseContentFromLink returns:
retrieval.ErrRobotsDenied
When image search succeeds at the HTTP level but nothing in the response is relevant
to the query, SearchImagesWithQuery returns:
retrieval.ErrNoRelevantImages
You can handle it explicitly:
doc, err := c.ParseContentFromLink(ctx, url, true)
if err != nil {
if errors.Is(err, retrieval.ErrRobotsDenied) {
// skip or handle in a policy-compliant way
return
}
return
}
_ = doc
The error includes:
- status code
- request URL
- a truncated response body (up to
MaxErrBodyBytes)
This is extremely helpful for debugging rate limits (429), blocks (403), and upstream failures (5xx).
Notes for production & LLM usage
-
Rate limits / blocks: DuckDuckGo may rate-limit or block aggressive traffic. Add caching, backoff, and reasonable concurrency.
-
Image search is flaky, and retrying does not fix it (IMPORTANT): Bing is a black
box, and it does not always answer the question it was asked. It will sometimes
respond 200 OK with a full grid of images that have nothing to do with the query
— asking for mechanical keyboard switches and getting Tarzan fan art, for example
— while the page title and the search box still echo the query you sent. Nothing on
the client side distinguishes the two cases before parsing.
A missing market accounts for a large part of this, which is why Market defaults
to en-US — it roughly doubled the share of queries that return anything usable;
see Market. It does not eliminate the problem: about a quarter of
queries still substitute with the market set. The substitution happens on Bing's
side, not ours — the response is a complete page, 200 OK, with the correct title
and the correct query echoed back, next to images for something else.
What remains is not random: in our measurements a query that substitutes does so
reproducibly, and which queries are affected drifts over days. Retrying is
therefore close to useless — repeated attempts, a fresh connection, and a fresh
cookie jar all recovered zero out of three poisoned queries. Cache successful
results; do not build a retry loop and expect it to help.
Relevance filtering is what turns a silent wrong answer into an explicit
ErrNoRelevantImages: substituted responses score near zero and get discarded.
Read that error as "Bing did not answer this query", not as "no such images exist".
-
Robots / Terms (IMPORTANT): Enforcement is now handled per-request via the third parameter of ParseContentFromLink.
- If
true, the library will fetch and parse robots.txt before the main request.
- If access is denied, it returns
retrieval.ErrRobotsDenied.
- It's strongly recommended to keep this enabled for third-party sites to comply with their crawling policies.
-
HTML extraction is heuristic: readability works very well for articles, but not for all pages.
-
Security: treat fetched content as untrusted input (sanitize before rendering; consider domain allow-lists).
Contributing
PRs are welcome.
- Keep changes minimal and well-tested.
- Prefer backward-compatible API extensions.
- If you change parsing logic, include HTML fixtures.
Please read:
CONTRIBUTING.md
CODE_OF_CONDUCT.md
License
MIT — see LICENSE.