Skip to content

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.

go
func New(cfg ...Config) (*Processor, error)

Parameters: at most one Config; when omitted, DefaultConfig() is used.

go
p, err := html.New(html.DefaultConfig())
if err != nil {
	log.Fatal(err)
}
defer p.Close()

Internal initialization:

New performs these steps in order:

  1. 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, and MaxDepth must be positive; MaxCacheEntries cannot be negative (0 is legal and disables the cache); none may exceed its upper bound.
  2. Pre-computes the format strings: InlineImageFormat/InlineLinkFormat are normalized (lowercased, whitespace-stripped, empty mapped to "none") and cached in imageFormat/linkFormat, avoiding repeated strings.ToLower in the hot path.
  3. Sets the Scorer: a custom Scorer is adapted to the internal interface automatically; otherwise the built-in default scorer is used (unexported, read-only, concurrency-safe).
  4. Starts cache cleanup: the background cleanup goroutine starts only when CacheTTL>0 and CacheCleanup>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: config never changes after New(), so format methods such as ExtractToMarkdown can 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/totalProcessTime all use atomic operations.
  • Cache: the internal cache carries its own lock. Cache behavior is observed and controlled through the public API: Config.MaxCacheEntries = 0 disables it, ClearCache() empties it, and Statistics.CacheHits/CacheMisses report hits.
  • Scorer: the built-in default scorer is read-only. A custom Scorer must ensure its own concurrency safety: one Processor calls its Score from multiple goroutines during concurrent Extract. ShouldRemove is consulted only while the built-in default scorer is in use; with a custom Scorer configured, node removal still follows the built-in rules.

Method Overview ​

Processor has 42 exported methods, grouped by function (signatures and behavior follow):

GroupMethodDescription
Content extractionProcessor.ExtractExtract a full Result from HTML bytes
Content extractionProcessor.ExtractWithContextSame, with context cancellation
Content extractionProcessor.ExtractFromFileExtract from an HTML file
Content extractionProcessor.ExtractFromFileWithContextSame, with context cancellation
Text extractionProcessor.ExtractTextExtract plain text only
Text extractionProcessor.ExtractTextWithContextSame, with context cancellation
Text extractionProcessor.ExtractTextFromFileExtract plain text from a file
Text extractionProcessor.ExtractTextFromFileWithContextSame, with context cancellation
Output formatsProcessor.ExtractToMarkdownOutput Markdown (temporary Processor, bypasses the main cache)
Output formatsProcessor.ExtractToMarkdownWithContextSame, with context cancellation
Output formatsProcessor.ExtractToMarkdownFromFileOutput Markdown from a file
Output formatsProcessor.ExtractToMarkdownFromFileWithContextSame, with context cancellation
Output formatsProcessor.ExtractToJSONOutput JSON (goes through the main cache)
Output formatsProcessor.ExtractToJSONWithContextSame, with context cancellation
Output formatsProcessor.ExtractToJSONFromFileOutput JSON from a file
Output formatsProcessor.ExtractToJSONFromFileWithContextSame, with context cancellation
Link extractionProcessor.ExtractAllLinksExtract all link resources (no content cleaning applied)
Link extractionProcessor.ExtractAllLinksWithContextSame, with context cancellation
Link extractionProcessor.ExtractAllLinksFromFileExtract links from a file
Link extractionProcessor.ExtractAllLinksFromFileWithContextSame, with context cancellation
Batch processingProcessor.ExtractBatchConcurrent batch extraction (byte-slice input)
Batch processingProcessor.ExtractBatchWithContextSame, with context cancellation
Batch processingProcessor.ExtractBatchFilesConcurrent batch extraction (file-path input)
Batch processingProcessor.ExtractBatchFilesWithContextSame, with context cancellation
Reader modeProcessor.ReadPageWhole-page sectioned view (*ReadResult, bypasses the cache)
Reader modeProcessor.ReadPageWithContextSame, with context cancellation
Reader modeProcessor.ReadPageFromFileRead whole-page sections from a file
Reader modeProcessor.ReadPageFromFileWithContextSame, with context cancellation
Reader modeProcessor.ReadPageToMarkdownWhole-page Markdown (with links, temporary Processor)
Reader modeProcessor.ReadPageToMarkdownWithContextSame, with context cancellation
Reader modeProcessor.ReadPageToMarkdownTextWhole-page Markdown (no links)
Reader modeProcessor.ReadPageToMarkdownTextWithContextSame, with context cancellation
Reader modeProcessor.ReadPageFromFileToMarkdownFile → Markdown (with links)
Reader modeProcessor.ReadPageFromFileToMarkdownWithContextSame, with context cancellation
Reader modeProcessor.ReadPageFromFileToMarkdownTextFile → Markdown (no links)
Reader modeProcessor.ReadPageFromFileToMarkdownTextWithContextSame, with context cancellation
Statistics & cacheProcessor.GetStatisticsReturn Statistics processing statistics
Statistics & cacheProcessor.ClearCacheClear the cache, keeping accumulated statistics
Statistics & cacheProcessor.ResetStatisticsReset all statistics counters
AuditProcessor.GetAuditLogReturn audit log entries held in memory
AuditProcessor.ClearAuditLogClear the audit log
LifecycleProcessor.CloseRelease 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:

ErrorTriggerNote
ErrProcessorClosedp is nil or already ClosedShared by the extraction, formatting, link, and batch methods
ErrInputTooLargeInput bytes exceed MaxInputSizeWrapped in *InputError with actual/limit sizes
Encoding detection errorEncoding detection or UTF-8 conversion failsThe underlying error is wrapped
ErrInvalidHTMLBytes cannot be parsed as HTMLThe parse error is wrapped too
ErrMaxDepthExceededElement nesting exceeds MaxDepthIterative check; prevents stack overflow
ErrProcessingTimeoutThe library's processing timeout elapsedProcessingTimeout=0 means unlimited
ErrInternalPanicAn unexpected internal panic was recoveredSafety net; should not occur in normal use
ErrTooManyConcurrentOpsThe 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:

ScenarioReturned 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 expirescontext.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 ​

go
func (p *Processor) Extract(htmlBytes []byte) (*Result, error)

Extract content from HTML bytes, detecting the encoding automatically.

ExtractFromFile ​

go
func (p *Processor) ExtractFromFile(filePath string) (*Result, error)

Extract content from a file.

ExtractText ​

go
func (p *Processor) ExtractText(htmlBytes []byte) (string, error)

Return the plain text only.

ExtractTextFromFile ​

go
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:

go
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 ​

go
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:

go
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

  • ExtractToMarkdown builds a temporary Processor (copying the immutable config, with MaxCacheEntries zeroed) 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.
  • ExtractToJSON calls p.Extract directly 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.

go
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 ​

go
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) *BatchResult

Input 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: CacheHits and TotalProcessed each increment by 1, and cloneResult is returned — a deep copy that copys slices such as Images/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, so AverageProcessTime is a true average that includes hits.
  • Miss path: the result is written to the cache, then a cloneResult is 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.

go
func (p *Processor) GetStatistics() Statistics

Statistics fields:

FieldDescription
TotalProcessedExtractions that completed without error, including cache hits
CacheHitsTimes served directly from the cache
CacheMissesMisses that required full processing
ErrorCountExtractions 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
AverageProcessTimeAverage wall-clock time per extraction (0 when TotalProcessed is 0)
go
stats := p.GetStatistics()
fmt.Printf("Processed: %d, Cache hits: %d\n",
	stats.TotalProcessed, stats.CacheHits)

ClearCache ​

Clear the cache, keeping accumulated statistics.

go
func (p *Processor) ClearCache()

ResetStatistics ​

Reset all statistics counters.

go
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.

go
func (p *Processor) GetAuditLog() []AuditEntry

ClearAuditLog ​

Clear the audit log.

go
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.

go
func (p *Processor) Close() error
go
p, err := html.New(cfg)
if err != nil {
	log.Fatal(err)
}
defer p.Close()
// ... use p for extraction

Lifecycle 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: place defer 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 ErrProcessorClosed after Close. Close is idempotent; repeated calls are safe but pointless.