useragent

repository·master·Indexed 19 days ago

https://github.com/mileusna/useragent

A Go package for parsing user agent strings to identify browsers, operating systems, device types, and bots. It provides the useragent.Parse() function to extract structured data into a UserAgent struct, including version numbers via the VersionNo struct for precise comparisons. The library includes shorthand boolean methods for common checks (e.g., IsChrome(), IsAndroid()) and supports categorization of devices as mobile, desktop, tablet, or bot.

Tokens
2.7K
Snippets
12
Records
14
Agent score
68%

What's inside useragent

  1. Understand user agent detection behavior and notices

    master

    When using the package, keep the following behaviors in mind:

    • Bots and Mobile: If a bot (like Googlebot) is detected using a mobile crawler, both ua.Bot and ua.Mobile will be set to true.
    • Opera vs Opera Mini: These are treated as two distinct browsers because they operate differently.
    • Unknown User Agents: The package uses a deterministic detection method. If a user agent string provides insufficient information, ua.IsUnknown() will return true. Note that even if unknown, fields like Name or OS might still contain partial information.
    • Deterministic Detection: The package attempts to identify the agent even if the string does not follow common formats.
  2. Use shorthand functions for browser and OS checks

    master

    Instead of manually comparing string values for ua.OS or ua.Name, you can use shorthand methods for common checks. This makes your code cleaner and less error-prone.

    Example comparison:

    Instead of:

    if ua.OS == "Android" && ua.Name == "Chrome" {
        // do something
    }

    Use:

    if ua.IsAndroid() && ua.IsChrome() {
        // do something
    }
    ua := useragent.Parse(userAgentString)
    if ua.IsAndroid() && ua.IsChrome() {
        // do something
    }
  3. Parse user agent strings with useragent.Parse()

    master

    Use the useragent.Parse(userAgent string) function to analyze a user agent string. It returns a UserAgent struct containing information about the browser, operating system, device type, and more.

    Extracted information includes:

    • Name and Version: The browser or bot name (e.g., Chrome, Firefox, Googlebot).
    • OS and OS Version: The operating system (e.g., Windows, Android, iOS).
    • Device Type: Categorization as mobile, desktop, tablet, or bot.
    • Device Name: Specific device model if available (e.g., iPhone, iPad).
    • Bot URL: The URL provided by the bot (e.g., http://www.google.com/bot.html).
    import "github.com/mileusna/useragent"
    
    ua := useragent.Parse("Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) ...")
    fmt.Println("Name:", ua.Name, "v", ua.Version)
    fmt.Println("OS:", ua.OS, "v", ua.OSVersion)
    fmt.Println("Device:", ua.Device)
    if ua.Mobile {
        fmt.Println("(Mobile)")
    }
  4. Parse and compare version numbers

    master

    The package provides a VersionNo struct that parses raw version strings (like 100.0.4896.127) into individual components (Major, Minor, Patch). This allows for precise version comparisons.

    Version Comparison

    You can perform logic based on specific version segments:

    if ua.IsChrome() && ua.VersionNo.Major < 100 {
        log.Println("Error, browser is too old")
    }

    Formatting Version Strings

    You can print prettified versions using the following methods:

    • Browser Versions: VersionNoShort() and VersionNoFull()
    • OS Versions: OSVersionNoShort() and OSVersionNoFull()

    Example Output:

    Chrome 100.0
    Chrome 100.0.4896
    fmt.Println(ua.Name, ua.VersionNoShort())
    fmt.Println(ua.Name, ua.VersionNoFull())
  5. Check operating systems with UserAgent shorthand functions

    master

    The UserAgent type provides shorthand boolean methods to quickly identify the operating system of a parsed user agent. These methods check the ua.OS field against known constants.

    Available OS checks:

    • IsWindows(): Returns true if OS is Windows.
    • IsAndroid(): Returns true if OS is Android.
    • IsMacOS(): Returns true if OS is MacOS.
    • IsIOS(): Returns true if OS is IOS.
    • IsLinux(): Returns true if OS is Linux.
    • IsChromeOS(): Returns true if OS is ChromeOS or CrOS.
    • IsBlackberryOS(): Returns true if OS is BlackBerry.
    // Assuming ua is an instance of UserAgent
    if ua.IsWindows() {
        // Handle Windows logic
    }
    
    if ua.IsAndroid() {
        // Handle Android logic
    }
  6. Check browser and bot names with UserAgent shorthand functions

    master

    The UserAgent type provides shorthand boolean methods to identify specific browsers or bots by checking the ua.Name field against known constants.

    Browser checks:

    • IsChrome(): Returns true if Name is Chrome.
    • IsFirefox(): Returns true if Name is Firefox.
    • IsInternetExplorer(): Returns true if Name is Internet Explorer.
    • IsSafari(): Returns true if Name is Safari.
    • IsEdge(): Returns true if Name is Edge.
    • IsOpera(): Returns true if Name is Opera.
    • IsOperaMini(): Returns true if Name is Opera Mini.
    • IsBlackBerry(): Returns true if Name is BlackBerry.

    Bot checks:

    • IsGooglebot(): Returns true if Name is Googlebot.
    • IsTwitterbot(): Returns true if Name is Twitterbot.
    • IsFacebookbot(): Returns true if Name is FacebookExternalHit.
    • IsYandexbot(): Returns true if Name is YandexBot.
    if ua.IsChrome() {
        // Handle Chrome logic
    }
    
    if ua.IsGooglebot() {
        // Handle Googlebot logic
    }
  7. Identify unknown user agents with IsUnknown()

    master

    The IsUnknown() method returns true if the package cannot reliably determine the device category. Specifically, it returns true if the user agent is not identified as Mobile, Tablet, Desktop, or Bot.

    if ua.IsUnknown() {
        // Handle cases where device type is unreliable
    }
  8. Format software version numbers

    master

    The UserAgent type provides methods to format the parsed software version into short or full semantic version strings. If the version components (Major, Minor, Patch) are all zero, these methods return an empty string "".

    // Returns <Major>.<Minor>
    short := ua.VersionNoShort()
    
    // Returns <Major>.<Minor>.<Patch>
    full := ua.VersionNoFull()
  9. Parse user agent strings with Parse()

    master

    Use the Parse function to convert a raw user agent string into a structured UserAgent struct. This struct contains extracted information about the operating system, browser name, version, device type (mobile, tablet, desktop), and whether the agent is a bot.

    package main
    
    import (
    	"fmt"
    	"github.com/mileusna/mileusna/useragent"
    )
    
    func main() {
    	ua := useragent.Parse("Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1")
    	fmt.Printf("OS: %s, Browser: %s, Mobile: %v\n", ua.OS, ua.Name, ua.Mobile)
    }
  10. Format operating system version numbers

    master

    The UserAgent type provides methods to format the parsed operating system version into short or full semantic version strings. If the OS version components (Major, Minor, Patch) are all zero, these methods return an empty string "".

    // Returns <Major>.<Minor>
    short := ua.OSVersionNoShort()
    
    // Returns <Major>.<Minor>.<Patch>
    full := ua.OSVersionNoFull()
  11. Compare operating systems and browsers using constants

    master

    The package provides several constants to avoid magic strings when performing comparisons on the UserAgent fields. Use these constants for reliable matching against ua.OS or ua.Name.

    // Operating Systems
    useragent.Windows
    useragent.WindowsPhone
    useragent.WindowsNT
    useragent.WindowsPhoneOS
    useragent.Android
    useragent.MacOS
    useragent.IOS
    useragent.Linux
    useragent.FreeBSD
    useragent.ChromeOS
    useragent.BlackBerry
    useragent.CrOS
    useragent.Harmony
    
    // Browsers
    useragent.Opera
    useragent.OperaMini
    useragent.OperaTouch
    useragent.Chrome
    useragent.HeadlessChrome
    useragent.Firefox
    useragent.InternetExplorer
    useragent.Safari
    useragent.Edge
    useragent.Vivaldi
    useragent.MobileSafari
    useragent.NetFront
    useragent.Mozilla
    useragent.Msie
    useragent.SamsungBrowser
    
    // Bots
    useragent.GoogleAdsBot
    useragent.Googlebot
    useragent.Twitterbot
    useragent.FacebookExternalHit
    useragent.Applebot
    useragent.Bingbot
    useragent.YandexBot
    useragent.YandexAdNet
    
    // Apps
    useragent.FacebookApp
    useragent.InstagramApp
    useragent.TiktokApp