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
- Variables
- func GetDeviceModel(lowerUA, deviceType string) string
- func ParseDeviceType(lowerUA string) string
- func ParseOS(lowerUA string) string
- type Browser
- type BrowserPattern
- type UserAgent
- func (ua UserAgent) BrowserInfo() Browser
- func (ua UserAgent) BrowserName() string
- func (ua UserAgent) BrowserVer() string
- func (ua UserAgent) DeviceModel() string
- func (ua UserAgent) DeviceType() string
- func (ua UserAgent) GetShortIdentifier() string
- func (ua UserAgent) IsBot() bool
- func (ua UserAgent) IsConsole() bool
- func (ua UserAgent) IsDesktop() bool
- func (ua UserAgent) IsMobile() bool
- func (ua UserAgent) IsTV() bool
- func (ua UserAgent) IsTablet() bool
- func (ua UserAgent) IsUnknown() bool
- func (ua UserAgent) OS() string
- func (ua UserAgent) String() string
- func (ua UserAgent) UserAgent() string
Constants ¶
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
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
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
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
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 ¶
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 ¶
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 ¶
ParseDeviceType classifies devices using fast string matching. Order matters: iOS devices first (common), then Android logic, then fallbacks.
Types ¶
type Browser ¶
func ParseBrowser ¶
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 Parse ¶
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 (UserAgent) BrowserName ¶
func (UserAgent) BrowserVer ¶
func (UserAgent) DeviceModel ¶
func (UserAgent) DeviceType ¶
func (UserAgent) GetShortIdentifier ¶
GetShortIdentifier creates human-readable session identifiers for logging and analytics. Handles various edge cases to provide consistent, useful output across all UA types.