useragent

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2025 License: MIT Imports: 5 Imported by: 1

README

go-useragent

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.GetBrowser())  // Chrome
    fmt.Println(agent.GetVersion())  // 118.0.0.0
    fmt.Println(agent.GetOS())       // Windows
    fmt.Println(agent.GetDevice())   // Desktop
    fmt.Println(agent.IsDesktop())  // true
    fmt.Println(agent.IsMobile())   // false
    fmt.Println(agent.IsTablet())   // false
    fmt.Println(agent.IsTV())       // false
    fmt.Println(agent.IsBot())      // false

    // Helper functions.
    fmt.Println(agent.GetMajorVersion())  // 118
}

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             308.3 ns/op               0 B/op          0 allocs/op
MileusnaParserGetSingle-12      1322602             917.3 ns/op             600 B/op         16 allocs/op
UAPParserGetSingle-12            986428              1159 ns/op             233 B/op          8 allocs/op

MedamaParserGetAll-12             71804             15544 ns/op               0 B/op          0 allocs/op
MileusnaParserGetAll-12           28375             42301 ns/op           28031 B/op        716 allocs/op
UAPParserGetAll-12                18645             56951 ns/op           10179 B/op        344 allocs/op

Acknowledgements

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Parser

type Parser struct {
	Trie *RuneTrie
}

func NewParser

func NewParser() *Parser

Create a new Trie and populate it with user agent data.

func (*Parser) Parse

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

Parse a user agent string and return a UserAgent struct.

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

type UserAgent

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

func (UserAgent) GetBrowser

func (ua UserAgent) GetBrowser() string

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

func (UserAgent) GetDevice added in v1.0.3

func (ua UserAgent) GetDevice() string

GetDevice returns the device type as a string.

func (UserAgent) GetMajorVersion

func (ua UserAgent) GetMajorVersion() string

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

func (UserAgent) GetOS

func (ua UserAgent) GetOS() string

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

func (UserAgent) GetVersion

func (ua UserAgent) GetVersion() string

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

func (UserAgent) IsBot

func (ua UserAgent) IsBot() bool

IsBot returns true if the user agent is a bot.

func (UserAgent) IsDesktop

func (ua UserAgent) IsDesktop() bool

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

func (UserAgent) IsMobile

func (ua UserAgent) IsMobile() bool

IsMobile returns true if the user agent is a mobile 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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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