useragent

package
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package useragent provides User-Agent string parsing to extract browser, operating system, and device information for web analytics, content optimization, and request handling.

The package identifies device types (mobile, desktop, tablet, bot, TV, console), specific device models, operating systems, and browser information with optimized bot detection for common crawlers and social media bots.

Basic Usage

Parse a User-Agent string and access the extracted information:

import "github.com/dmitrymomot/forge/pkg/useragent"

ua, err := useragent.Parse(r.Header.Get("User-Agent"))
if err != nil {
	log.Printf("Failed to parse User-Agent: %v", err)
	return
}

fmt.Printf("Device: %s\n", ua.DeviceType())    // "mobile"
fmt.Printf("OS: %s\n", ua.OS())                // "ios"
fmt.Printf("Browser: %s\n", ua.BrowserName())  // "safari"
fmt.Printf("Version: %s\n", ua.BrowserVer())   // "14.2"
fmt.Printf("Model: %s\n", ua.DeviceModel())    // "iphone"

Device Type Detection

Use device type constants and convenience methods:

switch ua.DeviceType() {
case useragent.DeviceTypeMobile:
	// Serve mobile UI
case useragent.DeviceTypeDesktop:
	// Serve desktop UI
case useragent.DeviceTypeTablet:
	// Serve tablet UI
case useragent.DeviceTypeBot:
	// Handle bot traffic
default:
	// Handle unknown devices
}

// Or use convenience methods
if ua.IsMobile() {
	fmt.Println("Mobile device detected")
}

if ua.IsBot() {
	fmt.Printf("Bot: %s\n", ua.GetShortIdentifier())
}

Error Handling

The package defines specific error types for different failure modes:

ua, err := useragent.Parse(userAgentString)
if err != nil {
	switch {
	case errors.Is(err, useragent.ErrEmptyUserAgent):
		// Handle empty User-Agent header
	case errors.Is(err, useragent.ErrUnknownDevice):
		// Handle unknown device type
	case errors.Is(err, useragent.ErrMalformedUserAgent):
		// Handle malformed User-Agent string
	default:
		// Handle other parsing errors
	}

	// Create fallback UserAgent for continued processing
	ua = useragent.New(userAgentString, "unknown", "", "unknown", "unknown", "")
}

Performance

The package uses fast-path lookups for common bots and keyword-based matching for device classification. Parsing typically takes 10-100 microseconds per request. For high-traffic applications, consider caching parsed results for identical User-Agent strings.

Index

Constants

View Source
const (
	// DeviceTypeBot identifies automated crawlers, bots, and spiders
	DeviceTypeBot = "bot"

	// DeviceTypeMobile identifies smartphones and feature phones
	DeviceTypeMobile = "mobile"

	// DeviceTypeTablet identifies tablet devices (iPad, Android tablets, etc.)
	DeviceTypeTablet = "tablet"

	// DeviceTypeDesktop identifies desktop computers and laptops
	DeviceTypeDesktop = "desktop"

	// DeviceTypeTV identifies smart TVs and streaming devices
	DeviceTypeTV = "tv"

	// DeviceTypeConsole identifies gaming consoles
	DeviceTypeConsole = "console"

	// DeviceTypeUnknown is used when the device type cannot be determined
	DeviceTypeUnknown = "unknown"
)

Device types represent the category of device that made the request

View Source
const (
	// MobileDeviceIPhone identifies Apple iPhone devices
	MobileDeviceIPhone = "iphone"

	// MobileDeviceAndroid identifies generic Android mobile devices
	MobileDeviceAndroid = "android"

	// MobileDeviceSamsung identifies Samsung mobile devices
	MobileDeviceSamsung = "samsung"

	// MobileDeviceHuawei identifies Huawei mobile devices
	MobileDeviceHuawei = "huawei"

	// MobileDeviceXiaomi identifies Xiaomi mobile devices
	MobileDeviceXiaomi = "xiaomi"

	// MobileDeviceOppo identifies Oppo mobile devices
	MobileDeviceOppo = "oppo"

	// MobileDeviceVivo identifies Vivo mobile devices
	MobileDeviceVivo = "vivo"

	// MobileDeviceUnknown is used when the mobile device model cannot be determined
	MobileDeviceUnknown = "unknown"
)

Mobile device model identifiers

View Source
const (
	// TabletDeviceIPad identifies Apple iPad tablets
	TabletDeviceIPad = "ipad"

	// TabletDeviceAndroid identifies generic Android tablets
	TabletDeviceAndroid = "android"

	// TabletDeviceSamsung identifies Samsung tablets
	TabletDeviceSamsung = "samsung"

	// TabletDeviceHuawei identifies Huawei tablets
	TabletDeviceHuawei = "huawei"

	// TabletDeviceKindleFire identifies Amazon Kindle Fire tablets
	TabletDeviceKindleFire = "kindle"

	// TabletDeviceSurface identifies Microsoft Surface tablets
	TabletDeviceSurface = "surface"

	// TabletDeviceUnknown is used when the tablet model cannot be determined
	TabletDeviceUnknown = "unknown"
)

Tablet device model identifiers

View Source
const (
	// BrowserChrome identifies Google Chrome browser
	BrowserChrome = "chrome"

	// BrowserFirefox identifies Mozilla Firefox browser
	BrowserFirefox = "firefox"

	// BrowserSafari identifies Apple Safari browser
	BrowserSafari = "safari"

	// BrowserEdge identifies Microsoft Edge browser
	BrowserEdge = "edge"

	// BrowserOpera identifies Opera browser
	BrowserOpera = "opera"

	// BrowserIE identifies Internet Explorer browser
	BrowserIE = "ie"

	// BrowserSamsung identifies Samsung Internet browser
	BrowserSamsung = "samsung"

	// BrowserUC identifies UC Browser
	BrowserUC = "uc"

	// BrowserQQ identifies QQ Browser
	BrowserQQ = "qq"

	// BrowserHuawei identifies Huawei Browser
	BrowserHuawei = "huawei"

	// BrowserVivo identifies Vivo Browser
	BrowserVivo = "vivo"

	// BrowserMIUI identifies Xiaomi MIUI Browser
	BrowserMIUI = "miui"

	// BrowserBrave identifies Brave Browser
	BrowserBrave = "brave"

	// BrowserVivaldi identifies Vivaldi Browser
	BrowserVivaldi = "vivaldi"

	// BrowserYandex identifies Yandex Browser
	BrowserYandex = "yandex"

	// BrowserUnknown is used when the browser cannot be determined
	BrowserUnknown = "unknown"
)

Browser name identifiers

View Source
const (
	// OSWindows identifies Microsoft Windows operating system
	OSWindows = "windows"

	// OSWindowsPhone identifies Microsoft Windows Phone operating system
	OSWindowsPhone = "windows phone"

	// OSMacOS identifies Apple macOS operating system
	OSMacOS = "macos"

	// OSiOS identifies Apple iOS mobile operating system
	OSiOS = "ios"

	// OSAndroid identifies Google Android operating system
	OSAndroid = "android"

	// OSLinux identifies Linux-based operating systems
	OSLinux = "linux"

	// OSChromeOS identifies Google Chrome OS operating system
	OSChromeOS = "chromeos"

	// OSHarmonyOS identifies Huawei HarmonyOS operating system
	OSHarmonyOS = "harmonyos"

	// OSFireOS identifies Amazon Fire OS operating system
	OSFireOS = "fireos"

	// OSUnknown is used when the operating system cannot be determined
	OSUnknown = "unknown"
)

Operating system identifiers

Variables

View Source
var (
	ErrEmptyUserAgent     = errors.New("empty user agent string")
	ErrMalformedUserAgent = errors.New("malformed user agent string")
	ErrUnsupportedBrowser = errors.New("unsupported browser")
	ErrUnsupportedOS      = errors.New("unsupported operating system")
	ErrUnknownDevice      = errors.New("unknown device type")
	ErrParsingFailed      = errors.New("failed to parse user agent")
)

Functions

func GetDeviceModel

func GetDeviceModel(lowerUA, deviceType string) string

GetDeviceModel identifies specific device brands for mobile and tablet devices. Returns empty string for other device types since model detection isn't meaningful.

func ParseDeviceType

func ParseDeviceType(lowerUA string) string

ParseDeviceType classifies devices using fast string matching. Order matters: iOS devices first (common), then Android logic, then fallbacks.

func ParseOS

func ParseOS(lowerUA string) string

ParseOS identifies operating systems using keyword matching. Order reflects typical web traffic patterns: Windows first, then mobile OSes.

Types

type Browser

type Browser struct {
	Name    string
	Version string
}

func ParseBrowser

func ParseBrowser(lowerUA string) Browser

type BrowserPattern

type BrowserPattern struct {
	Regex     *regexp.Regexp
	Name      string
	Keywords  []string
	Excludes  []string
	OrderHint int
}

BrowserPattern defines a pattern for detecting a browser

type UserAgent

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

UserAgent contains the parsed information from a user agent string

func New

func New(ua, deviceType, deviceModel, os, browserName, browserVer string) UserAgent

New creates a UserAgent struct with the provided parameters

func Parse

func Parse(ua string) (UserAgent, error)

Parse analyzes a user agent string and extracts device, OS, and browser information. Returns structured data with appropriate errors for various failure modes.

func (UserAgent) BrowserInfo

func (ua UserAgent) BrowserInfo() Browser

func (UserAgent) BrowserName

func (ua UserAgent) BrowserName() string

func (UserAgent) BrowserVer

func (ua UserAgent) BrowserVer() string

func (UserAgent) DeviceModel

func (ua UserAgent) DeviceModel() string

func (UserAgent) DeviceType

func (ua UserAgent) DeviceType() string

func (UserAgent) GetShortIdentifier

func (ua UserAgent) GetShortIdentifier() string

GetShortIdentifier creates human-readable session identifiers for logging and analytics. Handles various edge cases to provide consistent, useful output across all UA types.

func (UserAgent) IsBot

func (ua UserAgent) IsBot() bool

func (UserAgent) IsConsole

func (ua UserAgent) IsConsole() bool

func (UserAgent) IsDesktop

func (ua UserAgent) IsDesktop() bool

func (UserAgent) IsMobile

func (ua UserAgent) IsMobile() bool

func (UserAgent) IsTV

func (ua UserAgent) IsTV() bool

func (UserAgent) IsTablet

func (ua UserAgent) IsTablet() bool

func (UserAgent) IsUnknown

func (ua UserAgent) IsUnknown() bool

func (UserAgent) OS

func (ua UserAgent) OS() string

func (UserAgent) String

func (ua UserAgent) String() string

func (UserAgent) UserAgent

func (ua UserAgent) UserAgent() string

Jump to

Keyboard shortcuts

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