Skip to main content

SDKs

Go SDK

kloakd-go — one API for everything, idiomatic Go client with full module coverage

8 min read


Install

go get github.com/kloakd-dev/kloakd-go@v0.7.0

v0.7.0 | Go 1.18+ | zero dependencies (stdlib net/http)

Client

import kloakd "github.com/kloakd-dev/kloakd-go"

client := kloakd.MustNew(kloakd.Config{
    APIKey:         os.Getenv("KLOAKD_API_KEY"),
    OrganizationID: os.Getenv("KLOAKD_ORG_ID"),
    Timeout:        100 * time.Second, // the default; keep it above the API's 85 s hand-off
    MaxRetries:     3,
})

Quickstart — one call does everything

result, _ := client.Crawl(ctx, "https://example.com",
    &kloakd.CrawlOrchestratorOptions{
        MaxPages:      50,
        ExtractSchema: map[string]string{"title": "css:h1", "content": "css:article"},
    })

for _, page := range result.Pages {
    if page.Ok() {
        fmt.Printf("%s → %v\n", page.URL, page.StructuredData)
    }
}

That's it. Crawl() internally:

  1. Discovers all pages on the site (Webgrph BFS)
  2. Fetches each page through the anti-bot engine, which works out per site what it takes (a browser, a residential exit, a challenge solver) — no ForceBrowser needed
  3. Extracts structured data from each page if ExtractSchema is provided (Kolektr, using cached fetch artifacts — no second HTTP round-trip)

Per-page failures are caught and marked Success: false — the crawl never aborts on a single page error.

Primary method

client.Crawl()

result, _ := client.Crawl(ctx, "https://example.com",
    &kloakd.CrawlOrchestratorOptions{
        MaxDepth:      3,
        MaxPages:      100,
        ExtractSchema: map[string]string{"title": "css:h1", "price": "css:.price"},
    })

fmt.Printf("Discovered: %d pages\n", result.TotalPagesDiscovered)
fmt.Printf("Fetched:    %d\n", result.PagesFetched)
fmt.Printf("Failed:     %d\n", result.PagesFailed)

for _, page := range result.Pages {
    if page.Ok() {
        fmt.Printf("  %s %v\n", page.URL, page.StructuredData)
    } else if page.Error != nil {
        fmt.Printf("  %s FAILED: %s\n", page.URL, *page.Error)
    }
}

Parameters

| Parameter | Type | Default | Description | |---|---|---|---| | url | string | required | Seed URL to start crawling from | | MaxDepth | int | your plan's maximum | Maximum BFS depth (sent only when set) | | MaxPages | int | your plan's maximum | Maximum pages to crawl (sent only when set) | | ExtractSchema | map[string]string | nil | {field: "css:selector"} (the css: prefix is optional) | | ExtractFields | []SchemaField | nil | An explicit fields list (Name, Selector, Attribute) | | IncludeExternalLinks | bool | false | Follow off-domain links | | SessionArtifactID | string | "" | Reuse an authenticated session artifact (from Fetchyr) |

Returns: SiteCrawlResult

| Field | Type | Description | |---|---|---| | Success | bool | The crawl's own success | | URL | string | Seed URL | | TotalPagesDiscovered | int | Pages found during BFS | | PagesFetched | int | Pages successfully fetched | | PagesFailed | int | Pages that failed (included with Success: false) | | Pages | []CrawlPage | All pages with HTML and optional structured data | | CrawlArtifactID | *string | Artifact ID for the site hierarchy | | Error | *string | Error message if crawl failed entirely | | CrawlID | string | The crawl's id | | Status | string | The crawl's own status, including held_quota | | Held | bool | The crawl is held for quota (below) | | Message | *string | The API's note on the crawl's state, such as why it is held |

client.CrawlStream() — streaming

For long-running crawls, use the streaming version to receive progress events via a channel:

ch, _ := client.CrawlStream(ctx, "https://example.com",
    &kloakd.CrawlOrchestratorOptions{
        MaxPages:      500,
        ExtractSchema: map[string]string{"title": "css:h1"},
    })

for event := range ch {
    switch event.Type {
    case "page_fetched":
        fmt.Printf("[%d/%d] %s OK\n", *event.Page, *event.Total, *event.URL)
    case "page_failed":
        fmt.Printf("[%d/%d] %s FAIL: %s\n", *event.Page, *event.Total, *event.URL, *event.Error)
    case "crawl_complete":
        fmt.Println("Done")
    }
}

Event types

| Type | Description | |---|---| | discovery_complete | Discovery finished, fetch phase starting | | page_fetching | About to fetch page N of total | | page_fetched | Page fetched successfully | | page_failed | Page fetch failed (crawl continues) | | crawl_complete | All pages processed |

Low-level methods

Need fine-grained control? The individual modules are still available:

Evadr.Fetch()

page, _ := client.Evadr.Fetch(ctx, "https://example.com", nil)   // follows a 202 hand-off to the result
fmt.Printf("Status: %d\n", page.StatusCode)

Webgrph.Crawl()

crawl, _ := client.Webgrph.Crawl(ctx, "https://example.com",
    &kloakd.CrawlOptions{MaxDepth: 3, MaxPages: 100})   // waits; StartCrawl returns at once
fmt.Printf("%s: %d pages\n", crawl.CrawlID, crawl.TotalPages)

Kolektr.Extract()

result, _ := client.Kolektr.Extract(ctx, "https://example.com",
    &kloakd.ExtractOptions{
        SchemaSpec: map[string]interface{}{"fields": []map[string]string{
            {"name": "title", "selector": "h1"},
            {"name": "price", "selector": ".price"},
        }},
    })
for _, r := range result.Records {
    fmt.Println(r)
}

One record per item

SDK v0.6.0 and later. ExtractOptions.ItemSelector is sent as the API's item_selector.

result, _ := client.Kolektr.Extract(ctx, "https://books.toscrape.com/",
    &kloakd.ExtractOptions{
        ItemSelector: "article.product_pod",
        Fields: []kloakd.SchemaField{
            {Name: "title", Selector: "h3 a", Attribute: "title"},
            {Name: "price", Selector: "p.price_color"},
        },
    })
fmt.Println(result.TotalRecords)   // 20: one record per book

With 0.5.0, put item_selector in a SchemaSpec that has a fields key; it is sent as given:

opts := &kloakd.ExtractOptions{SchemaSpec: map[string]interface{}{
    "item_selector": "article.product_pod",
    "fields": []map[string]string{
        {"name": "title", "selector": "h3 a", "attribute": "title"},
        {"name": "price", "selector": "p.price_color"},
    },
}}

Each element matching the item selector is one record, with the field selectors read inside it (rules). Without it the page is one record.

Artifact chaining

Pass artifact IDs between low-level methods to skip redundant work:

page, _ := client.Evadr.Fetch(ctx, "https://example.com", nil)

opts := &kloakd.ExtractOptions{
    SchemaSpec: map[string]interface{}{"fields": []map[string]string{{"name": "title", "selector": "h1"}}},
}
if page.ArtifactID != nil {
    opts.FetchArtifactID = *page.ArtifactID
}
data, _ := client.Kolektr.Extract(ctx, "https://example.com", opts)

Error handling

result, err := client.Crawl(ctx, "https://example.com", nil)
if err != nil {
    var rle *kloakd.RateLimitError
    var qe *kloakd.QuotaExceededError
    var ae *kloakd.AuthenticationError
    switch {
    case errors.As(err, &rle):
        fmt.Printf("Rate limited. Retry after %ds\n", rle.RetryAfter)
    case errors.As(err, &qe):
        fmt.Println("GB allocation used up")
    case errors.As(err, &ae):
        fmt.Println("Invalid API key")
    default:
        fmt.Printf("Error: %v\n", err)
    }
}

Advanced namespaces

client.Skanyr    // Site store: resources, APIs, snapshots, diff, graph, timeline, search
client.Nexus     // Strategy engine
client.Parlyr    // Natural language queries
client.Fetchyr   // Logins & authenticated scraping

Crawls: held, partial, continue

A crawl whose organisation ran out of allowance is held (held_quota), not failed, and resumes by itself. Webgrph.Crawl and Webgrph.WaitForCrawl return it at once with Held true and Message the server's text. client.Crawl returns SiteCrawlResult with Held, CrawlID, Status and Message.

A crawl that stopped early ends completed with IsPartial true. CrawlResult also has PartialReason, Resumable, PagesDiscovered, PagesFetched and PagesUnfetched.

crawl, err := client.Webgrph.Crawl(ctx, "https://example.com", nil)
if err != nil {
    return err
}
if crawl.Held {
    fmt.Println("held for quota; it resumes by itself") // crawl.Message has the server's text
} else if crawl.Resumable {
    // an *ApiError with StatusCode 409 when the crawl cannot be continued
    if _, err := client.Webgrph.ContinueCrawl(ctx, crawl.CrawlID); err != nil {
        return err
    }
    crawl, err = client.Webgrph.WaitForCrawl(ctx, crawl.CrawlID, nil)
}

Login sessions

login, err := client.Fetchyr.StartLoginSession(ctx, "https://example.com/login", nil)
if err != nil {
    return err
}
fmt.Println(login.Status, login.Next)

if login.SessionArtifactID != nil {
    status, _ := client.Fetchyr.GetSession(ctx, *login.SessionArtifactID)
    fmt.Println(status.Status)
    // an *ApiError with StatusCode 409 when the session is not paused
    _, _ = client.Fetchyr.ResumeSession(ctx, status.ArtifactID)
}

LoginSessionOptions has Method, Cookies, UserAgent and Country. The flow is described under logins.

Batch jobs

batch, err := client.CreateBatchJob(ctx,
    []string{
        "https://books.toscrape.com/catalogue/page-1.html",
        "https://books.toscrape.com/catalogue/page-2.html",
    },
    &kloakd.BatchJobOptions{EntityType: "products", Fields: []string{"title", "price"}})
if err != nil {
    return err
}
batch, _ = client.GetBatchJob(ctx, batch.ID)
fmt.Println(batch.Status, batch.CompletedItems, batch.TotalItems)

_, _ = client.PauseBatchJob(ctx, batch.ID)
_, _ = client.ResumeBatchJob(ctx, batch.ID)
_, _ = client.CancelBatchJob(ctx, batch.ID)

page, _ := client.ListBatchJobs(ctx, &kloakd.ListBatchJobsOptions{Page: 1, PageSize: 20})
fmt.Println(page.Total, len(page.BatchJobs))

results, _ := client.GetBatchJobResults(ctx, batch.ID, &kloakd.BatchJobResultsOptions{Limit: 100})
for _, item := range results.Results {
    fmt.Println(item.JobID, item.Status, item.ExtractedData)
}

saved, _ := client.DownloadBatchJob(ctx, batch.ID, "batch.csv", "csv")
fmt.Println(saved.Path, saved.Bytes)

BatchJobOptions has ExtractionConfig, CrawlID, EntityType and Fields. A BatchJob has ID, Name, Status, TotalItems, CompletedItems, CreatedAt and Message. A control the batch's state does not allow returns an *ApiError with StatusCode 409 and Code invalid_batch_transition. A create or resume that could not be queued returns an *ApiError with StatusCode 503 and Code dispatch_failed. The limit on batches at once returns a *ConcurrencyLimitError; its ActiveCrawls holds the API's active_batches. The rules are on the batch jobs page.

Unified scrape

scrape, err := client.UnifiedScrape(ctx, "https://books.toscrape.com/",
    &kloakd.UnifiedScrapeOptions{Prompt: "extract all book titles and prices"})
if err != nil {
    return err
}
switch {
case scrape.Status == "failed": // Success is true even then: check Status
    fmt.Println("the scrape failed")
case scrape.AuthRequired:
    fmt.Println("login needed")
default:
    job, _ := client.GetUnifiedScrape(ctx, scrape.JobID)
    fmt.Println(job.Status, job.Result)
}

UnifiedScrapeOptions has Prompt, Mode, Schema, Options, Context, Constraints, SessionArtifactID, PollInterval and PollTimeout; a 202 hand-off is followed. See unified scrape for the failed and login answers.

Crawl-extract jobs and exports

Webgrph has StartCrawlExtract, CrawlExtract, GetCrawlExtract, WaitForCrawlExtract, ListCrawlExtractResults, AllCrawlExtractResults, ListCrawlExtractPages, ExportCrawlExtract, DownloadCrawlExtract and CancelCrawlExtract for the crawl-extract job.

SavedExport.Crawl (*ExportCrawl) is read from the response's X-Crawl-* headers: Status, IsPartial, PartialReason, PagesDiscovered, PagesFetched, PagesUnfetched, Cancelled and RootUnfetched. It is nil for a batch export.

Changes in 0.7.0

  • Nexus.Execute and Nexus.Knowledge, with NexusExecuteResult and NexusKnowledgeResult.

Each PageNode gains FetchStatus.

Next steps

Was this page helpful?