Documentation
¶
Overview ¶
Package uax is a high-performance, zero-allocation HTTP User-Agent parser for Go. It extracts browser, engine, OS, CPU, device, in-app browser, and bot information from User-Agent strings and Client Hints headers.
Index ¶
- type App
- type Bot
- type BotClass
- type BotRule
- type Brand
- type Browser
- type BrowserRule
- type CPU
- type CacheStats
- type CachedParser
- type ClientHints
- type Device
- type DeviceRule
- type Engine
- type Input
- type OS
- type Option
- func WithBotDetection(enabled bool) Option
- func WithCustomBotRules(rules []BotRule) Option
- func WithCustomBrowserRules(rules []BrowserRule) Option
- func WithCustomDeviceRules(rules []DeviceRule) Option
- func WithPostParseHook(fn PostParseHookFunc) Option
- func WithPreParseHook(fn PreParseHookFunc) Option
- type Parser
- func (p *Parser) DetectBot(ua string) Bot
- func (p *Parser) Parse(input Input) Result
- func (p *Parser) ParseInto(input Input, out *Result)
- func (p *Parser) ParseRequest(r *http.Request) Result
- func (p *Parser) ParseRequestInto(r *http.Request, out *Result)
- func (p *Parser) ParseString(ua string) Result
- type PostParseHookFunc
- type PreParseHookFunc
- type Result
- type ShardedCache
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type App ¶
type App struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Kind string `json:"kind,omitempty"`
}
App describes an in-app browser or wrapper application.
type Bot ¶
type Bot struct {
IsBot bool `json:"isBot,omitempty"`
Class BotClass `json:"class,omitempty"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Vendor string `json:"vendor,omitempty"`
IsVerified bool `json:"isVerified,omitempty"`
Confidence float64 `json:"confidence,omitempty"`
}
Bot describes a detected automated agent (crawler, bot, AI agent, etc.).
type BotClass ¶
type BotClass string
BotClass categorizes the type of automated agent.
const ( BotNone BotClass = "" // BotNone indicates no bot was detected. BotSearch BotClass = "search" // BotSearch identifies a search engine crawler. BotSocial BotClass = "social" // BotSocial identifies a social media crawler. BotMonitor BotClass = "monitor" // BotMonitor identifies an uptime or performance monitor. BotScraper BotClass = "scraper" // BotScraper identifies a generic web scraper. BotAI BotClass = "ai" // BotAI identifies an AI/LLM training or inference crawler. BotSEO BotClass = "seo-tool" // BotSEO identifies an SEO analysis tool. BotOther BotClass = "other" // BotOther covers automated agents that don't fit other categories. )
type BotRule ¶
type BotRule struct {
Token string
Name string
Class BotClass
Vendor string
Verified bool
Match string // "exact", "contains", "prefix", or "regex" (RE2 syntax)
}
BotRule is a user-facing bot detection rule.
type Browser ¶
type Browser struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Major string `json:"major,omitempty"`
Family string `json:"family,omitempty"`
Channel string `json:"channel,omitempty"`
}
Browser describes the detected web browser.
type BrowserRule ¶
type BrowserRule struct {
Token string
Name string
Family string
Engine string
Match string // "exact", "contains", "prefix", or "regex" (RE2 syntax)
}
BrowserRule is a user-facing browser detection rule.
type CPU ¶
type CPU struct {
Architecture string `json:"architecture,omitempty"`
Bits int `json:"bits,omitempty"`
}
CPU describes the processor architecture.
type CacheStats ¶
CacheStats reports the current state of a CachedParser's LRU cache.
type CachedParser ¶
type CachedParser struct {
// contains filtered or unexported fields
}
CachedParser wraps a Parser with an LRU cache to avoid re-parsing identical UA strings.
func NewCachedParser ¶
func NewCachedParser(p *Parser, maxSize int) *CachedParser
NewCachedParser creates a CachedParser backed by the given Parser with an LRU cache of maxSize entries. If maxSize is <= 0, it defaults to 1024.
func (*CachedParser) Parse ¶
func (c *CachedParser) Parse(input Input) Result
Parse parses an Input, using the cache for UA-only lookups and bypassing it when Client Hints are present.
func (*CachedParser) ParseString ¶
func (c *CachedParser) ParseString(ua string) Result
ParseString parses a raw UA string, returning a cached Result when available.
func (*CachedParser) Stats ¶
func (c *CachedParser) Stats() CacheStats
Stats returns a snapshot of the cache hit/miss counters and current entry count.
type ClientHints ¶
type ClientHints struct {
UA string `json:"ua,omitempty"`
Platform string `json:"platform,omitempty"`
PlatformVersion string `json:"platformVersion,omitempty"`
Arch string `json:"arch,omitempty"`
Model string `json:"model,omitempty"`
FullVersion string `json:"fullVersion,omitempty"`
FullVersionList string `json:"fullVersionList,omitempty"`
}
ClientHints holds parsed Sec-CH-UA-* header values.
func ClientHintsFromMap ¶
func ClientHintsFromMap(m map[string]string) ClientHints
ClientHintsFromMap creates ClientHints from a map of HTTP header name→value.
func (*ClientHints) ParseBrands ¶
func (ch *ClientHints) ParseBrands() []Brand
ParseBrands parses the Sec-CH-UA style header into brand entries. Format: "BrandA";v="1", "BrandB";v="2"
type Device ¶
type Device struct {
Type string `json:"type,omitempty"`
Vendor string `json:"vendor,omitempty"`
Model string `json:"model,omitempty"`
IsTouch bool `json:"isTouch,omitempty"`
IsPhone bool `json:"isPhone,omitempty"`
IsTablet bool `json:"isTablet,omitempty"`
IsDesktop bool `json:"isDesktop,omitempty"`
IsTV bool `json:"isTV,omitempty"`
}
Device describes the physical device.
type DeviceRule ¶
type DeviceRule struct {
Token string
Type string
Vendor string
Model string
Match string // "exact", "contains", "prefix", or "regex" (RE2 syntax)
}
DeviceRule is a user-facing device detection rule.
type Engine ¶
type Engine struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
}
Engine describes the browser rendering engine.
type Input ¶
type Input struct {
UAString string `json:"uaString"`
ClientHints ClientHints `json:"clientHints"`
}
Input holds everything needed to parse a user agent: the raw string and optional Client Hints headers for improved accuracy.
func (*Input) HasClientHints ¶
HasClientHints reports whether any Client Hints data is present.
type OS ¶
type OS struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Major string `json:"major,omitempty"`
Minor string `json:"minor,omitempty"`
Patch string `json:"patch,omitempty"`
}
OS describes the operating system.
type Option ¶
type Option func(*parserConfig)
Option configures a Parser.
func WithBotDetection ¶
WithBotDetection enables or disables bot/crawler detection.
func WithCustomBotRules ¶
WithCustomBotRules adds custom bot rules. Precedence is not simply "custom before builtin": exact-match rules are looked up in a single trie where the first-inserted rule for a given token wins, so a custom exact rule overrides a builtin exact rule for the same token. Non-exact rules (contains/prefix/regex) are only consulted when no exact rule matched the token, and are tried in insertion order (custom rules first, then builtins). Rules match against individual UA product tokens and, for bot detection, also against semicolon-separated parts of parenthesized UA comments (e.g. "compatible; Googlebot/2.1; ...") — not the whole UA string.
func WithCustomBrowserRules ¶
func WithCustomBrowserRules(rules []BrowserRule) Option
WithCustomBrowserRules adds custom browser rules. Precedence is not simply "custom before builtin": exact-match rules are looked up in a single trie where the first-inserted rule for a given token wins, so a custom exact rule overrides a builtin exact rule for the same token. Non-exact rules (contains/prefix/regex) are only consulted when no exact rule matched the token, and are tried in insertion order (custom rules first, then builtins). Rules match against individual UA product tokens — not the whole UA string.
func WithCustomDeviceRules ¶
func WithCustomDeviceRules(rules []DeviceRule) Option
WithCustomDeviceRules adds custom device rules. Precedence is not simply "custom before builtin": exact-match rules are looked up in a single trie where the first-inserted rule for a given token wins, so a custom exact rule overrides a builtin exact rule for the same token. Non-exact rules (contains/prefix/regex) are only consulted when no exact rule matched the token, and are tried in insertion order (custom rules first, then builtins). Exact rules match against individual UA product tokens; non-exact rules are also checked against the full text of parenthesized UA comments — in neither case against the whole UA string.
func WithPostParseHook ¶
func WithPostParseHook(fn PostParseHookFunc) Option
WithPostParseHook registers a function called after each parse.
func WithPreParseHook ¶
func WithPreParseHook(fn PreParseHookFunc) Option
WithPreParseHook registers a function called before each parse.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser is a reusable, concurrency-safe user-agent parser.
func (*Parser) DetectBot ¶
DetectBot is a quick bot-only detection path. Returns an empty Bot if bot detection is disabled via WithBotDetection(false).
func (*Parser) ParseRequest ¶
ParseRequest parses a User-Agent and Client Hints from an HTTP request. Extracts the User-Agent header and all Sec-CH-UA-* headers automatically. Returns an empty Result if r is nil.
func (*Parser) ParseRequestInto ¶ added in v0.2.0
ParseRequestInto is the zero-allocation variant of ParseRequest. It writes the result into the caller-provided *Result, avoiding a copy. Does nothing if r is nil.
func (*Parser) ParseString ¶
ParseString is a convenience wrapper that parses a raw UA string.
type PostParseHookFunc ¶
PostParseHookFunc is called after parsing completes with timing info.
type PreParseHookFunc ¶
type PreParseHookFunc func(input Input)
PreParseHookFunc is called before parsing begins.
type Result ¶
type Result struct {
UAString string `json:"uaString,omitempty"`
Browser Browser `json:"browser"`
Engine Engine `json:"engine"`
OS OS `json:"os"`
CPU CPU `json:"cpu"`
Device Device `json:"device"`
App App `json:"app"`
Bot Bot `json:"bot"`
IsMobile bool `json:"isMobile,omitempty"`
IsDesktop bool `json:"isDesktop,omitempty"`
IsTablet bool `json:"isTablet,omitempty"`
IsBot bool `json:"isBot,omitempty"`
IsCrawler bool `json:"isCrawler,omitempty"`
IsInApp bool `json:"isInApp,omitempty"`
}
Result holds the complete parsed output from a User-Agent string.
func Parse ¶
Parse parses a raw User-Agent string using the default global parser. Safe for concurrent use.
func (Result) DeviceClass ¶
DeviceClass returns the device type or "unknown" if not detected.
func (Result) ShortBrowser ¶
ShortBrowser returns a compact "Name Major" string, e.g. "Chrome 123".
type ShardedCache ¶
type ShardedCache struct {
// contains filtered or unexported fields
}
ShardedCache distributes cached entries across multiple independent LRU shards to reduce lock contention under high concurrency.
func NewShardedCache ¶
func NewShardedCache(p *Parser, shards, perShardSize int) *ShardedCache
NewShardedCache creates a sharded cache with the given number of shards and per-shard capacity. Total capacity = shards * perShardSize.
func (*ShardedCache) Parse ¶
func (sc *ShardedCache) Parse(input Input) Result
Parse parses an Input. Only caches if no Client Hints (CH makes each request unique).
func (*ShardedCache) ParseString ¶
func (sc *ShardedCache) ParseString(ua string) Result
ParseString parses a UA string with sharded caching.
func (*ShardedCache) Stats ¶
func (sc *ShardedCache) Stats() CacheStats
Stats returns aggregated cache statistics across all shards.
Source Files
¶
- bot.go
- cache.go
- clienthints.go
- custom_rules.go
- hooks.go
- input.go
- match_app.go
- match_bot.go
- match_browser.go
- match_cpu.go
- match_device.go
- match_engine.go
- match_os.go
- matcher.go
- merge.go
- parser.go
- request.go
- result.go
- rules_gen_app.go
- rules_gen_bot.go
- rules_gen_browser.go
- rules_gen_device.go
- rules_gen_engine.go
- sharded_cache.go
- tokenizer.go
- trie.go
- uax.go
- version.go