Compile the rule once, scan a byte slice, and read the matching rule names from the result. This example looks for hello, ignoring case.
Browser playground
Section titled “Browser playground”Run go-yara v0.11.1 locally in your browser. Rules and input bytes are not uploaded. The first scan downloads a 12.9 MiB runtime.
Scanner not loaded.
Matched rules
String occurrences
Occurrences can belong to rules whose conditions are false. Offsets and lengths are in bytes.
| Rule | String | Offset | Length |
|---|
Evidence findings
All captured values are omitted before results leave the worker. Field names, offsets, and lengths remain visible. Redaction applies to results; the input editor still shows the source.
A ready finding has complete extraction data. It does not establish that a credential is valid. No credential checks or network requests are made by the scanner.
Playground limits
16 KiB of rule source, 1 MiB of input, and three seconds for compilation and scanning. Each scan uses a fresh worker with a hard 128 MiB Wasm linear-memory ceiling and a soft 64 MiB Go runtime memory target. Browser and JavaScript overhead are additional; this is not a total tab-memory limit.
Results show at most 100 rule names and 200 occurrences, within 64 KiB of result JSON. Evidence copies at most 256 bytes per capture inside the worker and displays at most 20 findings and 80 field rows. These share the same result JSON budget. Display truncation happens after condition evaluation and correlation. If a scan runs out of time or memory, it produces no complete result. Cancellation discards the worker; browser timer delays can affect when it stops.
Select an example for text, hex, occurrence counts, a false condition, or credential evidence. Selection fills the editors; Compile and scan starts the local worker. The evidence examples show ready, partial, ambiguous, and truncated captures. Captured values are redacted before leaving the worker; field names, byte spans, and extraction status remain visible. The input editor still contains the original text.
The playground does not validate credentials or contact services. The credential evidence examples show how a Go application can pass complete findings to a separate validator.
Create a Go module
Section titled “Create a Go module”With Go installed, create an empty directory and add go-yara:
mkdir yara-examplecd yara-examplego mod init example.com/yara-examplego get github.com/cawalch/go-yara/compiler@v0.11.1See installation for the required Go version and CLI downloads.
Compile and scan
Section titled “Compile and scan”Save this as main.go:
package main
import ( "context" "fmt" "log"
"github.com/cawalch/go-yara/compiler")
func main() { program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `rule greeting { strings: $text = "hello" nocase condition: $text}`) if err != nil { log.Fatal(err) } result, err := program.Scan([]byte("Hello from Go")) if err != nil { log.Fatal(err) } for _, match := range result.MatchedRules { fmt.Println(match.Rule) }}Run it:
go run .The output is:
greetingThe rule matches because the input contains Hello. Changing the input to Goodbye produces no output. Compilation and scanning return separate errors; handle both in application code.
Reuse the program
Section titled “Reuse the program”Keep the compiled program when scanning more than one input. Its convenience methods manage pooled scanners, and the program supports concurrent scans. For custom options or repeated scans in one worker, create a reusable scanner.
Compile files and inspect rejected rules
Section titled “Compile files and inspect rejected rules”Use CompileFileWithContext(ctx, path) for a rule file. Relative include paths resolve from the containing file’s directory. For source strings containing relative includes, set the compiler’s base directory with SetBaseDir before compilation. import makes a registered module namespace available to the rules; include loads another rule file.
Compilation normally fails on an invalid rule. For an ingestion workflow that deliberately accepts a reduced rule set, WithIgnoreInvalidRules(true) keeps valid rules and reports omissions through GetIgnoredRules. Dependencies on rejected rules are omitted too; an invalid global rule can therefore remove otherwise valid rules. Fatal program-level errors still return an error.
Complete Go example: inspect omitted rules and their dependents
package main
import ( "context" "fmt" "log" "sort"
"github.com/cawalch/go-yara/compiler")
func main() { if err := run(); err != nil { log.Fatal(err) }}
func run() error { const source = `rule broken { condition: missing_identifier }rule dependent { condition: broken }rule good { condition: true }` _, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), source) fmt.Printf("strict compilation fails: %t\n", err != nil) c := compiler.NewCompiler(compiler.WithIgnoreInvalidRules(true)) program, err := c.CompileSourceWithContext(context.Background(), source) if err != nil { return err } // Fatal errors still stop compilation. ignored := c.GetIgnoredRules() sort.Slice(ignored, func(i, j int) bool { return ignored[i].Rule < ignored[j].Rule }) for _, diagnostic := range ignored { fmt.Printf("omitted: %s\n", diagnostic.Rule) // A diagnostic also carries Phase, Message, Line, and Column for reports. } matches, err := program.MatchingRules(nil) if err != nil { return err } for _, match := range matches { fmt.Printf("matched: %s\n", match.Rule) } return nil}strict compilation fails: trueomitted: brokenomitted: dependentmatched: goodInspect each diagnostic’s Phase, Message, Line, Column, and dependency information before accepting the resulting program. A successful tolerant compile does not mean every submitted rule is active. Keep strict compilation for workflows that require the whole rule set.
Semantic analysis and diagnostics
Section titled “Semantic analysis and diagnostics”Compilation checks the meaning of a parsed rule before producing an executable program. The semantic layer resolves identifiers and rule references, checks operator and function argument types, validates module fields against registered schemas, and rejects circular rule dependencies. Capture-group references and evidence declarations are checked here too.
- Parse sourceBuild an AST; resolve includes and imports
- Validate meaningNames, types, module signatures, dependencies, evidence
- Compile programSearch plans and condition bytecode
Forward references to other rules are allowed; dependency cycles are rejected. A well-typed rule can still encounter undefined values when it runs. For example, string.to_int("oops") is a valid function call whose result is undefined. Use defined when the condition needs to distinguish that case. Semantic analysis does not inspect future input bytes or establish whether an extracted credential works.
Complete Go example: inspect semantic diagnostics and runtime undefined values
package main
import ( "context" "errors" "fmt" "log"
"github.com/cawalch/go-yara/compiler" "github.com/cawalch/go-yara/semantic")
func main() { if err := run(); err != nil { log.Fatal(err) }}
func run() error { cases := []struct{ name, source string }{ {"forward reference", `rule first { condition: second } rule second { condition: true }`}, {"unknown name", `rule bad { condition: missing_identifier }`}, {"argument type", `import "math" rule bad { condition: math.in_range("x", 0.0, 1.0) }`}, {"dependency cycle", `rule first { condition: second } rule second { condition: first }`}, {"capture group", `rule bad { strings: $a = /(a)/ capture(value = 2) condition: $a }`}, } for _, example := range cases { c := compiler.NewCompiler() _, err := c.CompileSourceWithContext(context.Background(), example.source) if err == nil { fmt.Printf("%s: accepted\n", example.name) continue } var diagnostic *semantic.Error if !errors.As(err, &diagnostic) { return err } fmt.Printf("%s: %s\n", example.name, diagnostic.Code) // GetErrors returns all compiler diagnostics, with Phase, Code, Line, // Column, and Message. The wrapped semantic.Error above is the first. for _, item := range c.GetErrors() { if item.Phase != "semantic" || item.Line < 1 || item.Column < 1 { return fmt.Errorf("missing semantic diagnostic location (phase=%s line=%d col=%d): %w", item.Phase, item.Line, item.Column, item) } } } // A well-typed call can still produce undefined for a particular value. program, err := compiler.NewCompiler().CompileSourceWithContext(context.Background(), `import "string"rule conversion { condition: defined string.to_int("oops") }`) if err != nil { return err } matched, err := program.Matches(nil) if err != nil { return err } fmt.Printf("runtime conversion: compiled=true defined=%t\n", matched) return nil}forward reference: acceptedunknown name: undefined-identifierargument type: invalid-argument-typedependency cycle: circular-dependencycapture group: invalid-evidenceruntime conversion: compiled=true defined=falseCompiler.GetErrors() exposes compiler diagnostics with Phase, Code, Message, Line, and Column. For semantic failures, the returned error wraps the first semantic.Error; errors.As retrieves its code, position, rule, and optional suggestion. Use structured codes for classification and the message for display. Parsing and later compilation failures do not necessarily wrap a semantic error.
Most applications should compile through compiler, which resolves includes and supplies the registered module signatures and schemas to the validator. The exported semantic.Validator also accepts an AST for tooling that already owns one. A standalone validator needs the applicable module definitions; semantic.NewValidator() does not populate the compiler’s built-in module registry.
See the semantic error reference and compiler diagnostic reference. Custom field types and function signatures are described under modules and host data.