uagenerator

package module
v0.2.0 Latest Latest
Warning

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

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

README

ua-generator-go

A random user-agent generator for Go >= 1.22

Forked from github.com/130347665/ua-generator-go by Ekin Karadeniz. Licensed under Apache 2.0.

Features

  • No external dependencies.
  • No external user-agent list, no downloads.
  • User-agent versions are hardcoded into the code.
  • Platform and browser versions are based on real releases.
  • Client Hints (Sec-CH-UA fields).
  • Easy to integrate into HTTP clients.
  • Concurrency-safe.

Install

go get github.com/130347665/ua-generator-go

Note: Upgrade ua-generator periodically to keep user-agent versions up to date.

Basic usage

package main

import (
    "fmt"
    uagenerator "github.com/130347665/ua-generator-go"
)

func main() {
    ua, err := uagenerator.Generate(nil)
    if err != nil {
        panic(err)
    }
    fmt.Println(ua) // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/604.1.38 ...
}

Customization

It takes three different parameters to customize the user-agent.

device   := []string{"desktop", "mobile"}
platform := []string{"windows", "macos", "ios", "linux", "android"}
browser  := []string{"chrome", "edge", "firefox", "safari"}

Note: All parameters are optional and multiple values can be specified using slices.

Customized user-agent generation:
ua, _ := uagenerator.Generate(&uagenerator.GenerateConfig{
    Device:  []string{"desktop"},
    Browser: []string{"chrome", "edge"},
})

fmt.Println(ua.Text)         // Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 ...
fmt.Println(ua.Platform)     // windows
fmt.Println(ua.Browser)      // chrome
fmt.Println(ua.CH.Brands)    // "Not A(Brand";v="99", "Chromium";v="129", "Google Chrome";v="129"
fmt.Println(ua.CH.Mobile)    // ?0
fmt.Println(ua.CH.Platform)  // "Windows"

Headers

ua, _ := uagenerator.Generate(&uagenerator.GenerateConfig{
    Browser: []string{"chrome", "edge"},
})

// Returns a map with user-agent and low-entropy Client Hints:
headers := ua.Headers.Get()
// map[user-agent:Mozilla/5.0 ... sec-ch-ua:... sec-ch-ua-mobile:?0 sec-ch-ua-platform:"Windows"]

// Extend Client Hints via Accept-CH:
ua.Headers.AcceptCH("Sec-CH-UA-Platform-Version, Sec-CH-UA-Full-Version-List")
headers = ua.Headers.Get()
// Now also includes sec-ch-ua-platform-version and sec-ch-ua-full-version-list
Integrating into net/http:
ua, _ := uagenerator.Generate(&uagenerator.GenerateConfig{
    Browser: []string{"chrome", "edge"},
})

req, _ := http.NewRequest("GET", "https://httpbin.org/get", nil)
for k, v := range ua.Headers.Get() {
    req.Header.Set(k, v)
}
resp, _ := http.DefaultClient.Do(req)

Options

WeightedVersions

Increase the probability of the latest versions being chosen. Default is false.

ua, _ := uagenerator.Generate(&uagenerator.GenerateConfig{
    Browser: []string{"chrome", "edge"},
    Options: &uagenerator.Options{
        WeightedVersions: true,
    },
})
VersionRanges

Choose only versions within specified ranges. Default is nil.

ua, _ := uagenerator.Generate(&uagenerator.GenerateConfig{
    Browser: []string{"chrome"},
    Options: &uagenerator.Options{
        VersionRanges: map[string]uagenerator.VersionRange{
            "chrome": uagenerator.NewVersionRange(125, 129), // Between 125 and 129
            "edge":   uagenerator.NewVersionRange(120, 0),   // 120 minimum (0 = no max)
        },
    },
})

Note: If there is no valid version within the range, the filter will skip it and return a random valid version instead.

TiedSafariVersion

Make Safari version tied to macOS/iOS version. Default is false.

ua, _ := uagenerator.Generate(&uagenerator.GenerateConfig{
    Platform: []string{"macos", "ios"},
    Browser:  []string{"safari"},
    Options: &uagenerator.Options{
        TiedSafariVersion: true,
    },
})

License

Apache License 2.0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidDevice   = errors.New("uagenerator: invalid device type")
	ErrInvalidPlatform = errors.New("uagenerator: invalid platform")
	ErrInvalidBrowser  = errors.New("uagenerator: invalid browser")
)
View Source
var (
	Fixed           = core.Fixed
	Range           = core.Range
	NewVersion      = core.NewVersion
	WithPartitions  = core.WithPartitions
	WithLimit       = core.WithLimit
	WithSeparator   = core.WithSeparator
	WithTrimZero    = core.WithTrimZero
	NewVersionRange = core.NewVersionRange
)

Re-exported constructors and options — delegate to core.

View Source
var Browsers = []string{"chrome", "edge", "firefox", "safari"}

Valid browsers.

View Source
var BrowsersSupportCH = []string{"chrome", "edge"}

BrowsersSupportCH lists browsers that support Client Hints.

View Source
var Devices = []string{"desktop", "mobile"}

Valid device types.

View Source
var Platforms = []string{"windows", "macos", "ios", "linux", "android"}

Valid platforms.

View Source
var PlatformsDesktop = []string{"windows", "macos", "linux"}

PlatformsDesktop lists platforms available on desktop devices.

View Source
var PlatformsMobile = []string{"ios", "android"}

PlatformsMobile lists platforms available on mobile devices.

Functions

func CHBool

func CHBool(val bool) string

CHBool formats a boolean as a Client Hints boolean value ("?1" or "?0").

func CHBrandList

func CHBrandList(brands []Brand) string

CHBrandList formats a list of brands as a Client Hints brand list. Example output: `"Not A(Brand";v="99", "Chromium";v="103", "Google Chrome";v="103"`

func CHList

func CHList(list []string) string

CHList formats a string slice as a quoted comma-separated Client Hints list. Example: CHList([]string{"Desktop"}) returns `"Desktop"`.

func CHString

func CHString(val string) string

CHString formats a string as a quoted Client Hints string value. Example: CHString("Windows") returns `"Windows"` (with literal quotes).

func Contains

func Contains(slice []string, val string) bool

Contains checks if a string slice contains a given value.

Types

type AndroidVersion

type AndroidVersion = core.AndroidVersion

Type aliases — fully transparent to all external code.

type AndroidVersionSpec

type AndroidVersionSpec = core.AndroidVersionSpec

Type aliases — fully transparent to all external code.

type Brand

type Brand struct {
	Brand   string
	Version string
}

Brand represents a browser brand with its version string.

type ChromiumVersion

type ChromiumVersion = core.ChromiumVersion

Type aliases — fully transparent to all external code.

type ChromiumVersionSpec

type ChromiumVersionSpec = core.ChromiumVersionSpec

Type aliases — fully transparent to all external code.

type ClientHints

type ClientHints struct {
	Mobile                string // "?0" or "?1"
	Platform              string // e.g., `"Windows"` (quoted)
	PlatformVersion       string // e.g., `"13.0.0"` (quoted)
	Brands                string // e.g., `"Not A(Brand";v="99", "Chromium";v="129", "Google Chrome";v="129"`
	BrandsFullVersionList string // full version list
	BrowserVersion        string // e.g., `"129"` (quoted, major only)
	BrowserFullVersion    string // e.g., `"129.0.6668.116"` (quoted)
	Bitness               string // e.g., `"64"` (quoted)
	Architecture          string // e.g., `"x86"` (quoted)
	FormFactors           string // e.g., `"Desktop"`
	Model                 string // e.g., `"SM-G998U"` (quoted, Android only)
	Wow64                 string // "?0" or "?1"
	// contains filtered or unexported fields
}

ClientHints contains computed Sec-CH-UA header field values.

func NewClientHints

func NewClientHints(gen *GeneratorData) *ClientHints

NewClientHints creates a ClientHints by eagerly computing all fields from the given Generator.

type FormatOption

type FormatOption = core.FormatOption

Type aliases — fully transparent to all external code.

type GenerateConfig

type GenerateConfig struct {
	Device   []string // e.g., []string{"desktop"}, []string{"desktop", "mobile"}
	Platform []string // e.g., []string{"windows", "macos"}
	Browser  []string // e.g., []string{"chrome", "edge"}
	Options  *Options
}

GenerateConfig holds parameters for user-agent generation. All fields are optional. Nil or zero value means no constraint.

type GeneratorData

type GeneratorData = core.GeneratorData

GeneratorData holds the subset of generator fields needed by ClientHints.

type Headers

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

Headers manages HTTP headers including User-Agent and Client Hints.

func NewHeaders

func NewHeaders(userAgent, browser string, ch *ClientHints) *Headers

NewHeaders creates a Headers instance with default headers populated.

func (*Headers) AcceptCH

func (h *Headers) AcceptCH(val string)

AcceptCH parses a comma-separated Accept-CH header value and adds the corresponding Client Hints headers. This resets existing headers first. If the browser doesn't support Client Hints, this is a no-op (only resets).

func (*Headers) Add

func (h *Headers) Add(key string)

Add adds a specific Client Hints header to the header set.

func (*Headers) Get

func (h *Headers) Get() map[string]string

Get returns a copy of the current headers map.

func (*Headers) Reset

func (h *Headers) Reset()

Reset rebuilds the headers from scratch. The base user-agent header is always included. For Chrome and Edge, low-entropy Client Hints (sec-ch-ua, sec-ch-ua-mobile, sec-ch-ua-platform) are included by default.

func (*Headers) String

func (h *Headers) String() string

String returns the headers formatted as "key: value\n" lines.

type IntOrRange

type IntOrRange = core.IntOrRange

Type aliases — fully transparent to all external code.

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

Navigator provides data matching the JavaScript navigator.userAgentData API.

func NewNavigator

func NewNavigator(ch *ClientHints) *Navigator

NewNavigator creates a Navigator from a ClientHints.

func (n *Navigator) Get() map[string]any

Get returns a map matching the NavigatorUAData structure. Keys: brands, mobile, platform, architecture, bitness, formFactors, fullVersionList, model, platformVersion, wow64

type Options

type Options = core.Options

Options configures user-agent generation behavior.

type SafariVersion

type SafariVersion = core.SafariVersion

Type aliases — fully transparent to all external code.

type SafariVersionSpec

type SafariVersionSpec = core.SafariVersionSpec

Type aliases — fully transparent to all external code.

type UserAgent

type UserAgent struct {
	Device    string
	Platform  string
	Browser   string
	Text      string
	CH        *ClientHints
	Headers   *Headers
	Navigator *Navigator
}

UserAgent is the result of user-agent generation.

func Generate

func Generate(cfg *GenerateConfig) (*UserAgent, error)

Generate creates a random UserAgent. Pass nil for default (fully random) config.

func (*UserAgent) String

func (ua *UserAgent) String() string

String returns the user-agent text.

type Version

type Version = core.Version

Type aliases — fully transparent to all external code.

type VersionRange

type VersionRange = core.VersionRange

Type aliases — fully transparent to all external code.

type VersionSpec

type VersionSpec = core.VersionSpec

Type aliases — fully transparent to all external code.

type WindowsVersion

type WindowsVersion = core.WindowsVersion

Type aliases — fully transparent to all external code.

type WindowsVersionSpec

type WindowsVersionSpec = core.WindowsVersionSpec

Type aliases — fully transparent to all external code.

Directories

Path Synopsis
cmd
update-bot command
internal

Jump to

Keyboard shortcuts

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