useragent

package module
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2025 License: MIT Imports: 16 Imported by: 3

README

go-useragent

Go Reference

go-useragent is a high-performance zero-allocation Go library designed to parse browser name and version, operating system, and device type information from user-agent strings with sub-microsecond parsing times.

It achieves this efficiency by using a modified hybrid trie data structure to store and rapidly look up user-agent tokens. It utilizes heuristic rules, tokenizing a list of user-agent strings into a trie during startup. During runtime, the parsing process involves a straightforward lookup operation.

This project is actively maintained and used by the lightweight website analytics project Medama.

Installation

go get -u github.com/medama-io/go-useragent

Usage

This type of parser is typically initialized once at application startup and reused throughout the application's lifecycle. While it doesn't offer the exhaustive coverage of traditional regex-based parsers, it can be paired with one to handle unknown edge cases, where the trie-based parser acts as a fast path for the majority of user-agents.

Example

package main

import (
    "fmt"
    "github.com/medama-io/go-useragent"
)

func main() {
	// Create a new parser. Initialize only once during application startup.
	ua := useragent.NewParser()

	// Example user-agent string.
	str := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"

	// Parse the user-agent string.
	agent := ua.Parse(str)

	// Access parsed information using agent fields.
	fmt.Println(agent.Browser())        // agents.BrowserChrome
	fmt.Println(agent.BrowserVersion()) // 118.0.0.0
	fmt.Println(agent.OS())             // agents.OSWindows
	fmt.Println(agent.Device())         // agents.DeviceDesktop

	// Boolean helper functions.
	fmt.Println(agent.IsChrome())  // true
	fmt.Println(agent.IsFirefox()) // false

	fmt.Println(agent.IsWindows()) // true
	fmt.Println(agent.IsLinux())   // false

	fmt.Println(agent.IsDesktop()) // true
	fmt.Println(agent.IsTV())      // false
	fmt.Println(agent.IsBot())     // false
	// and many more...

	// Version helper functions.
	fmt.Println(agent.BrowserVersionMajor()) // 118
	fmt.Println(agent.BrowserVersionMinor()) // 0
	fmt.Println(agent.BrowserVersionPatch()) // 0.0
}

Refer to the pkg.go.dev documentation for more details on available fields and their meanings.

Benchmarks

Benchmarks were performed against ua-parser/uap-go and mileusena/useragent on an Apple M3 Pro Processor.

cd ./benchmarks
go test -bench=. -benchmem ./...

MedamaParserGetSingle-12        3871813             287.2 ns/op               0 B/op          0 allocs/op
MileusnaParserGetSingle-12      1322602             945.1 ns/op             600 B/op         16 allocs/op
UAPParserGetSingle-12            986428              1112 ns/op             233 B/op          8 allocs/op

MedamaParserGetAll-12             75219             14616 ns/op               0 B/op          0 allocs/op
MileusnaParserGetAll-12           25644             46806 ns/op           28878 B/op        732 allocs/op
UAPParserGetAll-12                19263             54621 ns/op           10316 B/op        352 allocs/op

Acknowledgements

  • The library draws inspiration from the techniques outlined in this Raygun blog post.

Documentation

Overview

Example
// Create a new parser. Initialize only once during application startup.
ua := useragent.NewParser()

// Example user-agent string.
str := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"

// Parse the user-agent string.
agent := ua.Parse(str)

// Access parsed information using agent fields.
fmt.Println(agent.Browser())        // agents.BrowserChrome
fmt.Println(agent.BrowserVersion()) // 118.0.0.0
fmt.Println(agent.OS())             // agents.OSWindows
fmt.Println(agent.Device())         // agents.DeviceDesktop

// Boolean helper functions.
fmt.Println(agent.IsChrome())  // true
fmt.Println(agent.IsFirefox()) // false

fmt.Println(agent.IsWindows()) // true
fmt.Println(agent.IsLinux())   // false

fmt.Println(agent.IsDesktop()) // true
fmt.Println(agent.IsTV())      // false
fmt.Println(agent.IsBot())     // false
// and many more...

// Version helper functions.
fmt.Println(agent.BrowserVersionMajor()) // 118
fmt.Println(agent.BrowserVersionMinor()) // 0
fmt.Println(agent.BrowserVersionPatch()) // 0.0
Output:

Chrome
118.0.0.0
Windows
Desktop
true
false
true
false
true
false
false
118
0
0.0

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MemoryStats added in v1.2.1

type MemoryStats struct {
	NodeSize        int // Size of this node in bytes
	ChildrenArrSize int // Memory used by children array
	ResultSize      int // Memory used by result slice
	TotalSize       int // Total memory for this node
	ChildrenCount   int // Number of children
	ResultCount     int // Number of result items
}

MemoryStats contains memory usage statistics for a trie node

type Parser

type Parser struct {
	Trie *RuneTrie
}

func NewParser

func NewParser() *Parser

NewParser creates a new parser and populates it with the default embedded user agent data.

func NewParserWithFile added in v1.2.0

func NewParserWithFile(filePath string) (*Parser, error)

NewParserWithFile creates a new parser with user agent definitions loaded from a file.

The file should contain one user agent definition per line.

func NewParserWithURL added in v1.2.0

func NewParserWithURL(ctx context.Context, url string) (*Parser, error)

NewParserWithURL creates a new parser with user agent definitions loaded from a URL. It accepts a context for cancellation and timeout control.

The URL should serve content with one user agent definition per line.

func (*Parser) Parse

func (p *Parser) Parse(ua string) UserAgent

Parse a user agent string and return a UserAgent struct.

type ResultStats added in v1.2.1

type ResultStats struct {
	TotalMemoryBytes int64
	NodeCount        int64
	AvgBytesPerNode  float64
	LargestNode      int
	SmallestNode     int
	ArrayNodes       int64
}

type RuneTrie

type RuneTrie struct {
	// contains filtered or unexported fields
}

RuneTrie is a trie of runes with string keys and interface{} values.

func NewRuneTrie

func NewRuneTrie() *RuneTrie

NewRuneTrie allocates and returns a new *RuneTrie.

func (*RuneTrie) Get

func (trie *RuneTrie) Get(key string) UserAgent

Get returns the value stored at the given key. Returns nil for internal nodes or for nodes with a value of nil.

func (*RuneTrie) GetMemoryStats added in v1.2.1

func (trie *RuneTrie) GetMemoryStats() MemoryStats

GetMemoryStats returns accurate memory usage statistics for this node.

func (*RuneTrie) GetTotalMemoryStats added in v1.2.1

func (trie *RuneTrie) GetTotalMemoryStats() ResultStats

GetTotalMemoryStats returns aggregate memory statistics for the entire trie

func (*RuneTrie) Put

func (trie *RuneTrie) Put(key string)

Put inserts the value into the trie at the given key, replacing any existing items. At the end of key tokens, a result is stored marking a potential match for a browser, device, or OS using the indexes provided by MatchTokenIndexes.

func (*RuneTrie) WalkMemoryStats added in v1.2.1

func (trie *RuneTrie) WalkMemoryStats(callback func(stats MemoryStats))

WalkMemoryStats walks the entire trie and calls the callback for each node

type UserAgent

type UserAgent struct {
	// contains filtered or unexported fields
}

func (UserAgent) Browser added in v1.1.0

func (ua UserAgent) Browser() agents.Browser

Browser returns the browser name. If no browser is found, it returns an empty string.

func (UserAgent) BrowserVersion added in v1.1.0

func (ua UserAgent) BrowserVersion() string

BrowserVersion returns the browser version. If no version is found, it returns an empty string.

func (UserAgent) BrowserVersionMajor added in v1.1.0

func (ua UserAgent) BrowserVersionMajor() string

BrowserVersionMajor returns the major version of the browser. If no version is found, it returns an empty string.

func (UserAgent) BrowserVersionMinor added in v1.1.0

func (ua UserAgent) BrowserVersionMinor() string

BrowserVersionMinor returns the minor version of the browser. If no version is found, it returns an empty string.

func (UserAgent) BrowserVersionPatch added in v1.1.0

func (ua UserAgent) BrowserVersionPatch() string

BrowserVersionPatch returns the patch version of the browser. If no version is found, it returns an empty string.

Note: The patch version may include a suffix (e.g., "1.2.3b").

func (UserAgent) Device added in v1.1.0

func (ua UserAgent) Device() agents.Device

Device returns the device type as a string.

func (UserAgent) GetBrowser deprecated

func (ua UserAgent) GetBrowser() string

GetBrowser returns the browser name. If no browser is found, it returns an empty string.

Deprecated: Use .Browser() instead.

func (UserAgent) GetDevice deprecated added in v1.0.3

func (ua UserAgent) GetDevice() string

GetDevice returns the device type as a string.

Deprecated: Use .Device() instead.

func (UserAgent) GetMajorVersion deprecated

func (ua UserAgent) GetMajorVersion() string

GetMajorVersion returns the major version of the browser. If no version is found, it returns an empty string.

Deprecated: Use .BrowserVersionMajor() instead.

func (UserAgent) GetOS deprecated

func (ua UserAgent) GetOS() string

GetOS returns the operating system name. If no OS is found, it returns an empty string.

Deprecated: Use .OS() instead.

func (UserAgent) GetVersion deprecated

func (ua UserAgent) GetVersion() string

GetVersion returns the browser version. If no version is found, it returns an empty string.

Deprecated: Use .BrowserVersion() instead.

func (UserAgent) IsAndroidBrowser added in v1.1.0

func (ua UserAgent) IsAndroidBrowser() bool

IsAndroidBrowser returns true if the user agent is an Android browser.

func (UserAgent) IsAndroidOS added in v1.1.0

func (ua UserAgent) IsAndroidOS() bool

IsAndroidOS returns true if the user agent is an Android OS device.

func (UserAgent) IsBot

func (ua UserAgent) IsBot() bool

IsBot returns true if the user agent is a bot.

func (UserAgent) IsChrome added in v1.1.0

func (ua UserAgent) IsChrome() bool

IsChrome returns true if the user agent is a Chrome browser.

func (UserAgent) IsChromeOS added in v1.1.0

func (ua UserAgent) IsChromeOS() bool

IsChromeOS returns true if the user agent is a Chrome OS device.

func (UserAgent) IsDesktop

func (ua UserAgent) IsDesktop() bool

IsDesktop returns true if the user agent is a desktop browser.

func (UserAgent) IsEdge added in v1.1.0

func (ua UserAgent) IsEdge() bool

IsEdge returns true if the user agent is an Edge browser.

func (UserAgent) IsFalkon added in v1.1.0

func (ua UserAgent) IsFalkon() bool

IsFalkon returns true if the user agent is a Falkon browser.

func (UserAgent) IsFirefox added in v1.1.0

func (ua UserAgent) IsFirefox() bool

IsFirefox returns true if the user agent is a Firefox browser.

func (UserAgent) IsIE added in v1.1.0

func (ua UserAgent) IsIE() bool

IsIE returns true if the user agent is an Internet Explorer browser.

func (UserAgent) IsIOS added in v1.1.0

func (ua UserAgent) IsIOS() bool

IsIOS returns true if the user agent is an iOS device.

func (UserAgent) IsLinux added in v1.1.0

func (ua UserAgent) IsLinux() bool

IsLinux returns true if the user agent is a Linux device.

func (UserAgent) IsMacOS added in v1.1.0

func (ua UserAgent) IsMacOS() bool

IsMacOS returns true if the user agent is a macOS device.

func (UserAgent) IsMobile

func (ua UserAgent) IsMobile() bool

IsMobile returns true if the user agent is a mobile browser.

func (UserAgent) IsNintendoBrowser added in v1.1.0

func (ua UserAgent) IsNintendoBrowser() bool

IsNintendoBrowser returns true if the user agent is a Nintendo browser.

func (UserAgent) IsOpenBSD added in v1.1.0

func (ua UserAgent) IsOpenBSD() bool

IsOpenBSD returns true if the user agent is an OpenBSD device.

func (UserAgent) IsOpera added in v1.1.0

func (ua UserAgent) IsOpera() bool

IsOpera returns true if the user agent is an Opera browser.

func (UserAgent) IsOperaMini added in v1.1.0

func (ua UserAgent) IsOperaMini() bool

IsOperaMini returns true if the user agent is an Opera Mini browser.

func (UserAgent) IsSafari added in v1.1.0

func (ua UserAgent) IsSafari() bool

IsSafari returns true if the user agent is a Safari browser.

func (UserAgent) IsSamsungBrowser added in v1.1.0

func (ua UserAgent) IsSamsungBrowser() bool

IsSamsungBrowser returns true if the user agent is a Samsung browser.

func (UserAgent) IsTV

func (ua UserAgent) IsTV() bool

IsTV returns true if the user agent is a TV browser.

func (UserAgent) IsTablet

func (ua UserAgent) IsTablet() bool

IsTablet returns true if the user agent is a tablet browser.

func (UserAgent) IsVivaldi added in v1.1.0

func (ua UserAgent) IsVivaldi() bool

IsVivaldi returns true if the user agent is a Vivaldi browser.

func (UserAgent) IsWindows added in v1.1.0

func (ua UserAgent) IsWindows() bool

IsWindows returns true if the user agent is a Windows device.

func (UserAgent) IsYandexBrowser added in v1.1.0

func (ua UserAgent) IsYandexBrowser() bool

IsYandexBrowser returns true if the user agent is a Yandex browser.

func (UserAgent) OS added in v1.1.0

func (ua UserAgent) OS() agents.OS

OS returns the operating system name. If no OS is found, it returns an empty string.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL