Skip to content

Scan inputs and manage scanners

Docs for v0.11.1 · Go 1.27.0+ · Go API

Compile a rule set once and reuse its CompiledProgram. Choose the scan API based on where the bytes live and whether you need complete match details or only a boolean answer.

Each Go example below is a complete main.go. Use the module setup in the quickstart, then run it with go run ..

Input API Memory and evaluation behavior
A byte slice program.Scan(data) Evaluates complete rules against the supplied bytes.
An io.Reader stream program.ScanReader(reader) Uses a bounded sliding input window ($C+W$) and evaluates complete rule conditions.
A file path program.ScanFile(path) Opens the file and scans its contents.
One isolated memory block scanner.MatchingRulesInBlock(block, fileSize) Evaluates one block immediately, using absolute offsets; keeps no blocks between calls.
Sparse memory blocks program.NewBlockScanner() Accumulates blocks; Finish() evaluates complete conditions.

ScanReader and MatchesReader use bounded sliding input buffers ($C + W$). Accumulated occurrence spans, copied match bytes, and evidence are separate: total memory can grow with the number and size of matches. Block scanning retains supplied block data. For raw pattern searches without condition evaluation, the CLI’s literal streaming mode remains available.

For sparse scans, provide each block’s logical offset and set the logical file size when rules use filesize. If a pattern crosses a block boundary, supply overlapping bytes. The scanner does not reconstruct missing bytes between blocks.

Regex occurrences are finalized only after their decision horizon and boundary context are available, or at EOF. Unbounded expressions use libyara-compatible verification limits: 4,096 bytes for forward-only verification and 8,192 bytes for verification in both directions. Reader overlap is raised to the required horizon plus two boundary bytes when necessary. WithMaxMatchSpan remains an additional caller-selected cap; increasing it does not remove verification limits.

Recompile legacy unbounded regex artifacts that lack a finite horizon, or set an explicit WithMaxMatchSpan; otherwise reader scanning fails before consuming input. Treat any reader error as a failed scan, including an error returned while obtaining boundary lookahead. See upgrade guidance before reusing compiled caches.

Use BlockScanner when conditions must combine occurrences from several regions. Each Scan(base, data) copies the block and searches its patterns; Finish() evaluates conditions using the accumulated occurrences and supplied address space. filesize defaults to the highest block end unless you call SetFileSize. A gap between blocks does not supply zero-filled bytes.

Supplied address space · not to scale
0x0000–0x0001MZHeader block
0x0002–0x0fffNo supplied bytes
0x1000–0x1005needlePayload block
A pattern crossing a boundary needs a complete window
nee│ block boundary │dle
Overlapping window: needleSupply all six bytes together at 0x1000
Conditions can combine occurrences across regions. Pattern searching does not concatenate separate blocks. SetFileSize(0x2000) supplies a logical size, not missing byte contents.

This example first matches a header and a distant payload. It then shows that splitting needle into adjacent nee and dle blocks loses the pattern unless a supplied window contains the whole match. Reset() starts another logical input and clears the file-size override too.

Complete Go example: scan sparse regions and supply an overlapping window
main.go
package main
import (
"context"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
rule sparse {
strings: $header = "MZ" $payload = "needle"
condition: $header at 0 and $payload at 0x1000 and filesize == 0x2000
}`)
if err != nil {
return err
}
scanner := program.NewBlockScanner()
defer scanner.Close()
if err := scanner.SetFileSize(0x2000); err != nil {
return err
}
if err := scanner.Scan(0, []byte("MZ")); err != nil {
return err
}
if err := scanner.Scan(0x1000, []byte("needle")); err != nil {
return err
}
result, err := scanner.Finish()
if err != nil {
return err
}
fmt.Printf("sparse: %t; payload offset=%#x\n", result.RuleResults["sparse"], result.Matches["sparse"]["$payload"][0].Offset)
// Reset drops the previous blocks, matches, and logical file size.
scanner.Reset()
if err := scanner.SetFileSize(0x2000); err != nil {
return err
}
for _, block := range []compiler.MemoryBlock{
{Base: 0, Data: []byte("MZ")},
{Base: 0x1000, Data: []byte("nee")},
{Base: 0x1003, Data: []byte("dle")},
} {
if err := scanner.Scan(block.Base, block.Data); err != nil {
return err
}
}
result, err = scanner.Finish()
if err != nil {
return err
}
fmt.Printf("split without overlap: %t\n", result.RuleResults["sparse"])
// Supply a window containing the entire boundary-crossing pattern.
if err := scanner.Scan(0x1000, []byte("needle")); err != nil {
return err
}
result, err = scanner.Finish()
if err != nil {
return err
}
fmt.Printf("with complete overlapping window: %t\n", result.RuleResults["sparse"])
return nil
}
Output
sparse: true; payload offset=0x1000
split without overlap: false
with complete overlapping window: true

Keep overlapping bytes consistent. Size the overlap for the patterns you need to match; an unbounded regex has no fixed overlap that guarantees equivalence to a full-input scan. For independent memory events, use MatchingRulesInBlock instead: each call evaluates only its own block and cannot satisfy a condition using a previous event.

Scan returns a ScanResult. MatchedRules contains the rules whose conditions evaluated to true. RuleResults records boolean outcomes, while Matches records pattern occurrences. Pattern matches alone do not imply that the rule matched: its condition may still be false.

The method scanner.Matches(data) returns a boolean; the field result.Matches holds occurrences. They serve different purposes:

Call or field Question it answers
scanner.Matches(data) Did any reportable rule match?
scanner.MatchingRules(data) Which rules matched? Returns rule records without the all-rules outcome map.
result.MatchedRules Which rules matched in this detailed scan?
result.RuleResults[name] What was this evaluated rule’s condition result? Use the map’s presence check to distinguish absent entries from false.
result.Matches[rule][pattern] Where did this pattern occur, even if its rule condition was false?

Choose one scan method for the output your caller needs. The example calls all three to compare their contracts, so it performs three scans. Both rules find hello, but only present satisfies its condition. WithMatchData(2) copies just he; the occurrence’s full length remains five bytes.

Complete Go example: read rule outcomes, byte offsets, and copied match data
main.go
package main
import (
"context"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
rule present { strings: $a = "hello" condition: $a }
rule gated { strings: $a = "hello" condition: $a and filesize > 100 }`)
if err != nil {
return err
}
scanner := program.NewScanner(compiler.WithMatchData(2))
defer scanner.Close()
data := []byte("--hello--")
result, err := scanner.Scan(data)
if err != nil {
return err
}
for _, name := range []string{"present", "gated"} {
matches := result.Matches[name]["$a"]
fmt.Printf("%s: condition=%t occurrences=%d\n", name, result.RuleResults[name], len(matches))
for _, match := range matches {
fmt.Printf(" offset=%d length=%d copied=%q truncated=%t\n", match.Offset, match.Length, match.MatchedData, match.MatchedDataTruncated)
}
}
// These methods perform separate scans with smaller result contracts.
anyMatch, err := scanner.Matches(data)
if err != nil {
return err
}
fmt.Printf("any rule matched: %t\n", anyMatch)
names, err := scanner.MatchingRules(data)
if err != nil {
return err
}
for _, match := range names {
fmt.Printf("matched rule: %s\n", match.Rule)
}
return nil
}
Output
present: condition=true occurrences=1
offset=2 length=5 copied="he" truncated=true
gated: condition=false occurrences=1
offset=2 length=5 copied="he" truncated=true
any rule matched: true
matched rule: present

WithMatchData and WithMatchContext opt into copied matched bytes and surrounding bytes. They can expose sensitive input and increase result size. Their per-match byte limits do not cap the number of occurrences. For structured capture fields, use evidence extraction.

An absent rule result is not automatically a clean negative: filters, private rules, pruning, and result-suppression options affect reporting. PrunedRules identifies rules rejected by mandatory fixed-offset header checks. A scan error must be handled before consuming a result.

The browser playground includes local evidence examples with redacted results. The Go examples below retain capture data for explicit validator handoff.

Enable WithEvidence(maxCaptureBytes) on a dedicated scanner to extract named values from matched strings. A capture(...) modifier maps regex groups to field names; an evidence: declaration assembles those fields into findings. The result includes each capture’s bytes, source offset, length, and truncation flag, so a downstream validator does not need to repeat the extraction regex.

Extraction in go-yara
  1. Pattern matchCapture named fields and source spans
  2. CorrelationGroup fields around a secret anchor
  3. FindingReady, partial, or ambiguous
Validation in the calling application · complete findings only
  1. Schema checkExpected fields; no truncated values
  2. ValidatorOffline parser or configured service adapter
  3. Validation outcomeRecord separately from extraction status
A ready finding can still fail validation. Partial and ambiguous findings need review before a validator receives their values.

Evidence extraction leaves the rule’s boolean condition unchanged. Keep the rule result, extraction status, and validator outcome as separate fields in your report:

Extraction status Meaning Validator handling
ready Every declared field has one unambiguous, untruncated capture. Check the expected field schema, then pass the values to an application validator.
partial A field is missing or its copied data was truncated. Keep the finding for review; do not validate a prefix as a complete credential.
ambiguous Fields have competing candidates, or proximity assignment is tied. Preserve the candidates; do not pick the first combination.

ready describes extraction completeness. A complete credential can still be expired, revoked, synthetic, or rejected by its service. A timeout or unavailable validator leaves validity unknown.

Assemble credentials from a URI or nearby assignments

Section titled “Assemble credentials from a URI or nearby assignments”

This example extracts endpoint, username, and secret from a PostgreSQL-style URI or nearby configuration assignments. It scans each synthetic input separately, checks the rule result, and passes only ready findings to a validator function. The validator is a deterministic test double: its accepted and rejected outcomes demonstrate the handoff without making network requests.

Save this as main.go in a module with go-yara installed, then run go run .:

Credential extraction and validator handoff
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/cawalch/go-yara/compiler"
)
const rules = `
rule credential_candidate {
strings:
$uri = /postgres:\/\/([^: @\r\n]+):([^@\r\n]+)@([^\/ \r\n]+)/
capture(username = 1, secret = 2, endpoint = 3)
$user = /username=([^ \r\n]+)/ capture(username = 1)
$pass = /password=([^ \r\n]+)/ capture(secret = 1)
$host = /endpoint=([^ \r\n]+)/ capture(endpoint = 1)
evidence:
credential = (endpoint, username, secret) within 96 of secret
condition:
$uri or $pass
}`
type credential struct{ endpoint, username, secret string }
type validator func(context.Context, credential) (string, error)
// Only ready findings reach the validator. An error is unknown, not rejected.
func validate(ctx context.Context, finding compiler.EvidenceFinding, check validator) string {
if finding.Status != compiler.EvidenceStatusReady {
return "not checked"
}
values := make(map[string]string)
for _, name := range []string{"endpoint", "username", "secret"} {
captures := finding.Fields[name]
if len(captures) != 1 || captures[0].DataTruncated {
return "not checked"
}
values[name] = string(captures[0].Data)
}
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
outcome, err := check(ctx, credential{values["endpoint"], values["username"], values["secret"]})
if err != nil {
return "unknown"
}
return outcome
}
// A deterministic test double: no database connection or HTTP request is made.
func fixtureValidator(ctx context.Context, candidate credential) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
if candidate.endpoint != "db.example.test" {
return "", errors.New("endpoint is outside the fixture")
}
if candidate.username == "alice" && candidate.secret == "demo-only" {
return "accepted (fixture)", nil
}
return "rejected (fixture)", nil
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), rules)
if err != nil {
return err
}
for _, sample := range []struct {
name, input string
captureLimit int
}{
{"URI", "postgres://alice:demo-only@db.example.test", 256},
{"assignments", "endpoint=db.example.test\nusername=alice\npassword=demo-only", 256},
{"missing", "endpoint=db.example.test\npassword=demo-only", 256},
{"ambiguous", "endpoint=db.example.test\nusername=alice\nusername=bob\npassword=demo-only", 256},
{"truncated", "postgres://alice:demo-only@db.example.test", 4},
{"rejected", "postgres://alice:wrong-demo@db.example.test", 256},
{"unknown", "postgres://alice:demo-only@unconfigured.example.test", 256},
} {
scanner := program.NewScanner(compiler.WithEvidence(sample.captureLimit))
result, err := scanner.Scan([]byte(sample.input))
scanner.Close()
if err != nil {
return err
}
findings := result.Evidence["credential_candidate"]["credential"]
if !result.RuleResults["credential_candidate"] || len(findings) != 1 {
return fmt.Errorf("%s: expected one finding from a matched rule", sample.name)
}
finding := findings[0]
outcome := validate(context.Background(), finding, fixtureValidator)
// Keep candidate values out of logs; retain status and source spans instead.
fmt.Printf("%s: %s; %s\n", sample.name, finding.Status, outcome)
}
return nil
}
Output
URI: ready; accepted (fixture)
assignments: ready; accepted (fixture)
missing: partial; not checked
ambiguous: ambiguous; not checked
truncated: partial; not checked
rejected: ready; rejected (fixture)
unknown: ready; unknown

capture(username = 1, secret = 2, endpoint = 3) names the regex’s numbered groups; group 0 captures the whole match. Fields from the same outer match are grouped together before proximity assignment. For separate matches, within 96 of secret uses the byte gap between capture spans to assign candidates to the nearest eligible secret anchor. Ties and multiple candidates remain ambiguous. This is proximity correlation, not a parser for configuration records: a nearby field can belong to a different record. Scan records separately or narrow the rule when record boundaries matter.

The URI expression is deliberately limited. It is not a general connection-string parser and does not decode percent escapes or cover every PostgreSQL URI form. These fixtures illustrate extraction; they are not a maintained secret-detector corpus.

Replace fixtureValidator with an adapter for a service you operate when checking whether credentials are active. Configure the destination independently or require an exact allowlist match; an endpoint extracted from a scanned file must not choose arbitrary network destinations. Have the adapter honor the context deadline and return distinct accepted, rejected, and unknown outcomes. Keep secret bytes and raw authentication errors out of logs. Store the rule, declaration, source identity, capture offsets, extraction status, and validation outcome for traceability.

Some validation needs no service connection. This example captures a complete unencrypted PKCS#8 PEM block and passes its bytes through pem.Decode and x509.ParsePKCS8PrivateKey. It generates a disposable key in memory, then scans a second PEM block whose body is not a private key. Both are ready findings; only the first parses successfully.

Complete Go example: extract and parse a private key
Offline PKCS#8 validation
package main
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
const rules = `
rule private_key_candidate {
strings:
$pem = /-----BEGIN PRIVATE KEY-----\r?\n[A-Za-z0-9+\/=\r\n]+-----END PRIVATE KEY-----/
capture(secret = 0)
evidence:
key = (secret) within 0 of secret
condition:
$pem
}`
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
// Generate a disposable key in memory; never print or write it to disk.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
der, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return err
}
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), rules)
if err != nil {
return err
}
scanner := program.NewScanner(compiler.WithEvidence(8 * 1024))
defer scanner.Close()
for _, sample := range []struct {
name string
der []byte
}{
{"generated key", der},
{"invalid DER", []byte("not a private key")},
} {
input := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: sample.der})
result, err := scanner.Scan(input)
if err != nil {
return err
}
findings := result.Evidence["private_key_candidate"]["key"]
if !result.RuleResults["private_key_candidate"] || len(findings) != 1 {
return fmt.Errorf("%s: expected one key candidate", sample.name)
}
finding := findings[0]
captures := finding.Fields["secret"]
if finding.Status != compiler.EvidenceStatusReady || len(captures) != 1 || captures[0].DataTruncated {
return fmt.Errorf("%s: incomplete key capture", sample.name)
}
block, rest := pem.Decode(captures[0].Data)
if block == nil || block.Type != "PRIVATE KEY" || len(bytes.TrimSpace(rest)) != 0 {
return fmt.Errorf("%s: expected one complete PEM block", sample.name)
}
_, parseErr := x509.ParsePKCS8PrivateKey(block.Bytes)
fmt.Printf("%s: %s; PKCS#8 parsed=%t\n", sample.name, finding.Status, parseErr == nil)
}
return nil
}
Output
generated key: ready; PKCS#8 parsed=true
invalid DER: ready; PKCS#8 parsed=false

Successful parsing establishes that the captured bytes encode a private key supported by the parser. It does not establish ownership, deployment, or whether any service accepts that key. This example only handles BEGIN PRIVATE KEY blocks; encrypted keys and other encodings need separate parsing paths.

WithEvidence(256) caps each capture’s copied bytes, not total evidence memory or the number of findings. Capture.Length retains the full source span length; DataTruncated marks a shortened Data copy. Use separate input, time, and workload limits. Capture-bound strings retain all occurrences when evidence is enabled, even with WithFastScan, so proximity correlation has the occurrences it needs.

By default, capture bytes and finding containers belong to the returned result. They remain valid after the input is changed or the scanner is reused or closed; retain results only as long as needed. Starting in v0.10.0, WithBorrowedEvidence(true) aliases Capture.Data directly onto the caller’s scanned input slice with three-index capacity clipping and pools evidence containers on the scanner; keep the input buffer immutable and do not reuse the result after the input buffer changes or is recycled. AppendEvidenceJSON and WriteEvidenceJSON serialize evidence findings without reflection.

Read findings from result.Evidence[ruleName][declarationName]. Each finding has an anchor and a Fields map whose values are candidate capture slices. Capture.Offset and Capture.Length identify source bytes; Pattern and Group identify the extraction rule. Check RuleResults or MatchedRules when deciding which rule findings to act on, and treat captured values as sensitive data.

The evidence API reference describes the result types. The repository’s synthetic secret rules also cover AWS assignments, service-account JSON, and freeform tokens. These use go-yara’s capture/evidence syntax, which other YARA engines may reject.

One compiled programShared search tables and bytecode · configuration held fixed
Worker 1
Own scannerMatch storage, scratch buffers, bound data
Input A → scan → result
Input B → scan → result
Close when the worker finishes
Worker 2
Own scannerMatch storage, scratch buffers, bound data
Input A → scan → result
Input B → scan → result
Close when the worker finishes
Workers may run concurrently. Each scanner handles one scan at a time; its reusable state stays with that worker.

Create a scanner with program.NewScanner to reuse its state and options across scans. This example scans two inputs and prints false, then true:

Reusable scanner
package main
import (
"context"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
rule marker { strings: $a = "marker" condition: $a }`)
if err != nil {
return err
}
scanner := program.NewScanner(compiler.WithoutMatches(), compiler.WithoutRuleResults())
defer scanner.Close()
for _, data := range [][]byte{[]byte("clean"), []byte("a marker")} {
matched, err := scanner.Matches(data)
if err != nil {
return err
}
fmt.Println(matched)
}
return nil
}

Close a dedicated scanner when its worker finishes. A scanner is for sequential use; give each concurrent worker its own scanner. The compiled program can be shared. Do not mutate its configuration or call setters concurrently with scans, and keep input bytes unchanged for the duration of a scan.

Context-aware compilation and scan methods accept a context.Context. Cancellation is cooperative. For reader scans, cancelling the context cannot interrupt an underlying Read call that is already blocked; the reader or transport must provide its own deadline or close behavior.

Complete Go example: bound a reader and handle cancellation
main.go
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"time"
"github.com/cawalch/go-yara/compiler"
)
var errTooLarge = errors.New("input exceeds byte limit")
func readBounded(reader io.Reader, limit int64) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(reader, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, errTooLarge
}
return data, nil
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `rule marker { strings: $a="marker" condition: $a }`)
if err != nil {
return err
}
scanner := program.NewScanner()
defer scanner.Close()
// Read one extra byte to detect oversized input instead of silently scanning a prefix.
const limit = 8
_, err = readBounded(bytes.NewBufferString("marker plus extra"), limit)
fmt.Printf("oversized input rejected: %t\n", errors.Is(err, errTooLarge))
data, err := readBounded(bytes.NewBufferString("marker"), limit)
if err != nil {
return err
}
cancelled, cancel := context.WithCancel(context.Background())
cancel()
_, err = scanner.ScanWithContext(cancelled, data)
fmt.Printf("cancelled: %t\n", errors.Is(err, context.Canceled))
// The cancelled call did not establish a rule outcome. A new context can be used next.
ctx, stop := context.WithTimeout(context.Background(), time.Second)
defer stop()
result, err := scanner.ScanWithContext(ctx, data)
if err != nil {
return err
}
fmt.Printf("next scan matched: %t\n", result.RuleResults["marker"])
return nil
}
Output
oversized input rejected: true
cancelled: true
next scan matched: true

The reader example uses limit + 1 to detect oversize input. Reading exactly the limit and scanning that prefix could miss a pattern or change a filesize condition. A LimitReader bounds bytes read; it cannot unblock a stalled underlying reader. Give network readers their own transport deadline.

For repetitive inputs, match limits can bound the number of recorded string occurrences. WithMaxMatches and WithMaxMatchSpan address different costs: occurrence counts and the bytes considered for an individual regex match. Limiting matches can affect conditions that depend on counts or offsets.

See the scanner API reference for context-aware methods, hooks, and limit options.

Declare scalar external names in rule source, then bind their values on a scanner. This lets workers use different environments or policy settings with the same compiled program. The setter replaces the scanner’s external-value map; supply every value needed for the next scan. In this example the third update omits enabled, so defined enabled is false.

Complete Go example: replace per-scanner external values
main.go
package main
import (
"context"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
external environment
external enabled
rule production_marker {
strings: $a = "marker"
condition: defined enabled and enabled and environment == "production" and $a
}`)
if err != nil {
return err
}
scanner := program.NewScanner()
defer scanner.Close()
for _, values := range []map[string]any{
{"environment": "staging", "enabled": true},
{"environment": "production", "enabled": true},
{"environment": "production"}, // Replaces the previous map; enabled is now undefined.
} {
if err := scanner.SetExternalVariables(values); err != nil {
return err
}
matched, err := scanner.Matches([]byte("marker"))
if err != nil {
return err
}
fmt.Printf("environment=%s enabled=%v matched=%t\n", values["environment"], values["enabled"], matched)
}
return nil
}
Output
environment=staging enabled=true matched=false
environment=production enabled=true matched=true
environment=production enabled=<nil> matched=false

Supported values include booleans, representable integers, floats, and strings. Undeclared names or unsupported Go values cause binding errors. Check setter errors immediately. With the constructor option WithExternalVariables, binding errors surface when scanning. Setters and scans must not run concurrently on the same scanner.

External variables supply scalar values used by conditions. Structured modules supply typed fields, arrays, and dictionaries. Bind per-worker data on the scanner when concurrent scans need different values. The modules guide shows a complete binding example and explains missing values.

WithMatchHook can stop after the first matching public rule. MatchActionStopScan includes that rule in the result and returns no error. It stops delivery of later matches; their conditions may already have been evaluated. Track the stop decision in application state so a partial rule result is not mistaken for complete coverage.

A polling callback can return PollAbort to stop the scan with ErrScanAborted. Check the error with errors.Is. Polling runs at checkpoints during a scan. Use a context to set a scan deadline. PollThrottle requests a pause at the current checkpoint.

Complete Go example: distinguish stop-on-match from a poll abort
main.go
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `
rule first { strings: $a = "marker" condition: $a }
rule second { strings: $a = "marker" condition: $a }`)
if err != nil {
return err
}
stopped := false
first := compiler.NewScanner(program, compiler.WithMatchHook(func(*compiler.CompiledRule, compiler.RuleMatch) compiler.MatchAction {
stopped = true // Track incomplete rule coverage separately from the error.
return compiler.MatchActionStopScan
}))
defer first.Close()
result, err := first.Scan([]byte("marker"))
if err != nil {
return err
}
fmt.Printf("stop on match: rules=%d stopped=%t error=false\n", len(result.MatchedRules), stopped)
abort := compiler.NewScanner(program, compiler.WithPollHook(func(context.Context, compiler.PollProgress) (compiler.PollAction, time.Duration) {
return compiler.PollAbort, 0
}, 1))
defer abort.Close()
_, err = abort.Scan([]byte("marker"))
if err == nil {
return errors.New("poll abort unexpectedly succeeded")
}
if !errors.Is(err, compiler.ErrScanAborted) {
return fmt.Errorf("expected poll abort: %w", err)
}
fmt.Printf("poll abort: ErrScanAborted=%t\n", errors.Is(err, compiler.ErrScanAborted))
return nil
}
Output
stop on match: rules=1 stopped=true error=false
poll abort: ErrScanAborted=true

WithRuleGate can omit rules before evaluation, and MatchActionSkipRule omits the current matching rule from the returned matches. Both change the result contract. Use them only when the application deliberately accepts reduced coverage; gates also require care with rule dependencies. Keep callbacks short and synchronous. See hooks and scan metrics for observation-only callbacks, counter meanings, and phase timing.