Processor
Processor is the core processing engine of the HTML library. An instance holds the extraction cache, statistics counters, and audit log for its lifetime, which suits high-frequency calls; for one-off calls the package functions are enough.
Creation
New
Create a Processor instance, optionally passing a configuration.
func New(cfg ...Config) (*Processor, error)Parameters: at most one Config; when omitted, DefaultConfig() is used.
p, err := html.New(html.DefaultConfig())
if err != nil {
log.Fatal(err)
}
defer p.Close()Internal initialization:
New performs these steps in order:
- Validates the config: calls
Config.Validate(); an invalid config returns*ConfigError(errors.Is(err, ErrInvalidConfig)is true). It checks numeric bounds and format strings:MaxInputSize,WorkerPoolSize, andMaxDepthmust be positive;MaxCacheEntriescannot be negative (0is legal and disables the cache); none may exceed its upper bound. - Pre-computes the format strings:
InlineImageFormat/InlineLinkFormatare normalized (lowercased, whitespace-stripped, empty mapped to"none") and cached inimageFormat/linkFormat, avoiding repeatedstrings.ToLowerin the hot path. - Sets the Scorer: a custom
Scoreris adapted to the internal interface automatically; otherwise the built-in default scorer is used (unexported, read-only, concurrency-safe). - Starts cache cleanup: the background cleanup goroutine starts only when
CacheTTL>0andCacheCleanup>0; if either is 0, it does not start.
Concurrency Safety
What makes sharing safe
A Processor can be shared across goroutines without extra locking, for four reasons:
- Immutable config:
confignever changes afterNew(), so format methods such asExtractToMarkdowncan copy it into a temporary Processor without a lock, and format overrides never write back to the shared config. - Statistics counters:
TotalProcessed/CacheHits/CacheMisses/ErrorCount/totalProcessTimeall useatomicoperations. - Cache: the internal cache carries its own lock. Cache behavior is observed and controlled through the public API:
Config.MaxCacheEntries = 0disables it,ClearCache()empties it, andStatistics.CacheHits/CacheMissesreport hits. - Scorer: the built-in default scorer is read-only. A custom
Scorermust ensure its own concurrency safety: one Processor calls itsScorefrom multiple goroutines during concurrentExtract.ShouldRemoveis consulted only while the built-in default scorer is in use; with a customScorerconfigured, node removal still follows the built-in rules.
Method Overview
Processor has 42 exported methods, grouped by function (signatures and behavior follow):
| Group | Method | Description |
|---|---|---|
| Content extraction | Processor.Extract | Extract a full Result from HTML bytes |
| Content extraction | Processor.ExtractWithContext | Same, with context cancellation |
| Content extraction | Processor.ExtractFromFile | Extract from an HTML file |
| Content extraction | Processor.ExtractFromFileWithContext | Same, with context cancellation |
| Text extraction | Processor.ExtractText | Extract plain text only |
| Text extraction | Processor.ExtractTextWithContext | Same, with context cancellation |
| Text extraction | Processor.ExtractTextFromFile | Extract plain text from a file |
| Text extraction | Processor.ExtractTextFromFileWithContext | Same, with context cancellation |
| Output formats | Processor.ExtractToMarkdown | Output Markdown (temporary Processor, bypasses the main cache) |
| Output formats | Processor.ExtractToMarkdownWithContext | Same, with context cancellation |
| Output formats | Processor.ExtractToMarkdownFromFile | Output Markdown from a file |
| Output formats | Processor.ExtractToMarkdownFromFileWithContext | Same, with context cancellation |
| Output formats | Processor.ExtractToJSON | Output JSON (goes through the main cache) |
| Output formats | Processor.ExtractToJSONWithContext | Same, with context cancellation |
| Output formats | Processor.ExtractToJSONFromFile | Output JSON from a file |
| Output formats | Processor.ExtractToJSONFromFileWithContext | Same, with context cancellation |
| Link extraction | Processor.ExtractAllLinks | Extract all link resources (no content cleaning applied) |
| Link extraction | Processor.ExtractAllLinksWithContext | Same, with context cancellation |
| Link extraction | Processor.ExtractAllLinksFromFile | Extract links from a file |
| Link extraction | Processor.ExtractAllLinksFromFileWithContext | Same, with context cancellation |
| Batch processing | Processor.ExtractBatch | Concurrent batch extraction (byte-slice input) |
| Batch processing | Processor.ExtractBatchWithContext | Same, with context cancellation |
| Batch processing | Processor.ExtractBatchFiles | Concurrent batch extraction (file-path input) |
| Batch processing | Processor.ExtractBatchFilesWithContext | Same, with context cancellation |
| Reader mode | Processor.ReadPage | Whole-page sectioned view (*ReadResult, bypasses the cache) |
| Reader mode | Processor.ReadPageWithContext | Same, with context cancellation |
| Reader mode | Processor.ReadPageFromFile | Read whole-page sections from a file |
| Reader mode | Processor.ReadPageFromFileWithContext | Same, with context cancellation |
| Reader mode | Processor.ReadPageToMarkdown | Whole-page Markdown (with links, temporary Processor) |
| Reader mode | Processor.ReadPageToMarkdownWithContext | Same, with context cancellation |
| Reader mode | Processor.ReadPageToMarkdownText | Whole-page Markdown (no links) |
| Reader mode | Processor.ReadPageToMarkdownTextWithContext | Same, with context cancellation |
| Reader mode | Processor.ReadPageFromFileToMarkdown | File → Markdown (with links) |
| Reader mode | Processor.ReadPageFromFileToMarkdownWithContext | Same, with context cancellation |
| Reader mode | Processor.ReadPageFromFileToMarkdownText | File → Markdown (no links) |
| Reader mode | Processor.ReadPageFromFileToMarkdownTextWithContext | Same, with context cancellation |
| Statistics & cache | Processor.GetStatistics | Return Statistics processing statistics |
| Statistics & cache | Processor.ClearCache | Clear the cache, keeping accumulated statistics |
| Statistics & cache | Processor.ResetStatistics | Reset all statistics counters |
| Audit | Processor.GetAuditLog | Return audit log entries held in memory |
| Audit | Processor.ClearAuditLog | Clear the audit log |
| Lifecycle | Processor.Close | Release resources (idempotent). After close, the extraction, formatting, link, reader, and batch methods return ErrProcessorClosed |
Signatures, ReadResult / PageSection / SectionKind, and section semantics for the 12 reader-mode methods are in Reader Mode.
Content Extraction
Error Returns
The Extract method family returns explicit sentinel errors at each stage; check them with errors.Is:
| Error | Trigger | Note |
|---|---|---|
ErrProcessorClosed | p is nil or already Closed | Shared by the extraction, formatting, link, and batch methods |
ErrInputTooLarge | Input bytes exceed MaxInputSize | Wrapped in *InputError with actual/limit sizes |
| Encoding detection error | Encoding detection or UTF-8 conversion fails | The underlying error is wrapped |
ErrInvalidHTML | Bytes cannot be parsed as HTML | The parse error is wrapped too |
ErrMaxDepthExceeded | Element nesting exceeds MaxDepth | Iterative check; prevents stack overflow |
ErrProcessingTimeout | The library's processing timeout elapsed | ProcessingTimeout=0 means unlimited |
ErrInternalPanic | An unexpected internal panic was recovered | Safety net; should not occur in normal use |
ErrTooManyConcurrentOps | The timeout watchdog hit its process-wide limit (1000; the watchdog exists only when ProcessingTimeout>0) | A "too busy" state; no timeout occurred |
The context-aware variants return errors by these rules:
| Scenario | Returned error |
|---|---|
The library's ProcessingTimeout elapses (user ctx still live) | ErrProcessingTimeout |
| The user ctx deadline fires first (or at the same time) | context.DeadlineExceeded, passed through unchanged, not normalized |
The user calls cancel() | context.Canceled |
ProcessingTimeout=0 (unlimited) and the user ctx expires | context.DeadlineExceeded (no timeout goroutine is started) |
When the library timeout fires, the extraction goroutine exits at its next cooperative check. When the user ctx expires, the library returns immediately; the inner checks see the same ctx and stop as well, but the goroutine is not forcibly killed.
Extract
func (p *Processor) Extract(htmlBytes []byte) (*Result, error)Extract content from HTML bytes, detecting the encoding automatically.
ExtractFromFile
func (p *Processor) ExtractFromFile(filePath string) (*Result, error)Extract content from a file.
ExtractText
func (p *Processor) ExtractText(htmlBytes []byte) (string, error)Return the plain text only.
ExtractTextFromFile
func (p *Processor) ExtractTextFromFile(filePath string) (string, error)Extract plain text from a file.
Context Variants
Extraction, text, output, link, and batch methods all have context.Context variants:
func (p *Processor) ExtractWithContext(ctx context.Context, htmlBytes []byte) (*Result, error)
func (p *Processor) ExtractFromFileWithContext(ctx context.Context, filePath string) (*Result, error)
func (p *Processor) ExtractTextWithContext(ctx context.Context, htmlBytes []byte) (string, error)
func (p *Processor) ExtractTextFromFileWithContext(ctx context.Context, filePath string) (string, error)Output Formats
func (p *Processor) ExtractToMarkdown(htmlBytes []byte) (string, error)
func (p *Processor) ExtractToMarkdownFromFile(filePath string) (string, error)
func (p *Processor) ExtractToJSON(htmlBytes []byte) ([]byte, error)
func (p *Processor) ExtractToJSONFromFile(filePath string) ([]byte, error)Context-aware variants:
func (p *Processor) ExtractToMarkdownWithContext(ctx context.Context, htmlBytes []byte) (string, error)
func (p *Processor) ExtractToMarkdownFromFileWithContext(ctx context.Context, filePath string) (string, error)
func (p *Processor) ExtractToJSONWithContext(ctx context.Context, htmlBytes []byte) ([]byte, error)
func (p *Processor) ExtractToJSONFromFileWithContext(ctx context.Context, filePath string) ([]byte, error)The two output formats treat the cache differently
ExtractToMarkdownbuilds a temporary Processor (copying the immutableconfig, withMaxCacheEntrieszeroed) and does not touch the main cache; Markdown results are not cached. Statistics and audit still flow into the parent Processor's counters and log.ExtractToJSONcallsp.Extractdirectly and goes through the normal cache path, hitting/writing the main cache and updating statistics.
To have Markdown output cached as well, create a dedicated Processor with MarkdownConfig() and call Extract, or cache the output yourself.
Link Extraction
func (p *Processor) ExtractAllLinks(htmlBytes []byte) ([]LinkResource, error)
func (p *Processor) ExtractAllLinksFromFile(filePath string) ([]LinkResource, error)
func (p *Processor) ExtractAllLinksWithContext(ctx context.Context, htmlBytes []byte) ([]LinkResource, error)
func (p *Processor) ExtractAllLinksFromFileWithContext(ctx context.Context, filePath string) ([]LinkResource, error)Batch Processing
func (p *Processor) ExtractBatch(htmlContents [][]byte) *BatchResult
func (p *Processor) ExtractBatchWithContext(ctx context.Context, htmlContents [][]byte) *BatchResult
func (p *Processor) ExtractBatchFiles(filePaths []string) *BatchResult
func (p *Processor) ExtractBatchFilesWithContext(ctx context.Context, filePaths []string) *BatchResultInput guards run before dispatch: an empty batch returns an empty BatchResult directly (0 successes, 0 failures); above 10000 items, every input item gets an error wrapping ErrBatchTooLarge in BatchResult.Errors; a closed Processor returns ErrProcessorClosed for each item. See Batch Processing for the concurrency model and the result structure.
Statistics and Cache
Cache Behavior in Detail
With MaxCacheEntries > 0, Extract enables the cache:
- Hit path:
CacheHitsandTotalProcessedeach increment by 1, andcloneResultis returned — a deep copy thatcopys slices such asImages/Links/Videos/Audios. Caller mutations do not affect the cached entry, which also avoids data races on concurrent hits. The near-zero time of a hit still counts toward the total time, soAverageProcessTimeis a true average that includes hits. - Miss path: the result is written to the cache, then a
cloneResultis returned. The cache entry and the return value never alias. - Cache disabled: with
MaxCacheEntries = 0, cache-key generation and cache reads/writes are skipped entirely, at no cache cost.
GetStatistics
Return the current processing statistics.
func (p *Processor) GetStatistics() StatisticsStatistics fields:
| Field | Description |
|---|---|
TotalProcessed | Extractions that completed without error, including cache hits |
CacheHits | Times served directly from the cache |
CacheMisses | Misses that required full processing |
ErrorCount | Extractions that returned an error: oversized input, encoding-conversion failures, and errors during processing (library timeouts and cancellations land here); calls whose ctx was already canceled before processing started, calls rejected by a closed Processor, and file-read errors are not counted |
AverageProcessTime | Average wall-clock time per extraction (0 when TotalProcessed is 0) |
stats := p.GetStatistics()
fmt.Printf("Processed: %d, Cache hits: %d\n",
stats.TotalProcessed, stats.CacheHits)ClearCache
Clear the cache, keeping accumulated statistics.
func (p *Processor) ClearCache()ResetStatistics
Reset all statistics counters.
func (p *Processor) ResetStatistics()Audit
GetAuditLog
Retrieve the audit log entries held in memory. When auditing is disabled or no entries exist yet, an empty (non-nil) slice is returned — check for entries with len(entries) > 0, not a nil test.
func (p *Processor) GetAuditLog() []AuditEntryClearAuditLog
Clear the audit log.
func (p *Processor) ClearAuditLog()Lifecycle
Close
Release the resources held by the Processor. Call it when you are done. When an audit Sink is configured, the Sink's Close error is returned (MultiSink aggregates the errors of all its child Sinks); otherwise nil is returned. The one-shot close path inside package functions ignores this error.
func (p *Processor) Close() errorp, err := html.New(cfg)
if err != nil {
log.Fatal(err)
}
defer p.Close()
// ... use p for extractionLifecycle essentials
- Reuse one instance: in a long-running service (HTTP handler, worker), create one Processor and share it across concurrent requests; it is concurrency-safe, so there is no need for one per request.
defer Close()immediately: placedefer p.Close()right after creation so exceptional paths still stop the cleanup goroutine, clear the cache, and close the audit sink.- Never use after Close: extraction, formatting, link, and batch methods return
ErrProcessorClosedafterClose.Closeis idempotent; repeated calls are safe but pointless.