gadget – zgo.at/gadget Index | Examples | Files

package gadget

import "zgo.at/gadget"

Index

Examples

Functions

func ShortenUA

func ShortenUA(ua string) string

ShortenUA shortens a User-Agent string by replacing common strings with small tokens.

Use UnshortenUA() to reverse it.

Example:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36
~Z (~W NT 10.0; Win64; x64) ~a537.36 ~G ~c80.0.3987.132 ~s537.36

The goal is not to produce the shortest output, but to provide a reasonably short output while maintaining readability.

Inspired by: https://github.com/icza/gox/blob/master/netx/httpx/httpx.go

func UnshortenUA

func UnshortenUA(short string) string

UnshortenUA reverses ShortenUA().

Types

type UserAgent

type UserAgent struct {
	BrowserName    string
	BrowserVersion string
	OSName         string
	OSVersion      string
}

func Parse

func Parse(h http.Header) UserAgent

Parse attempts to retrieve the browser and system name from the set of headers.

func ParseUA

func ParseUA(uaHeader string) UserAgent

ParseUA parses a User-Agent header.

Example

Code:play 

package main

import (
	"fmt"

	"zgo.at/gadget"
)

func main() {
	ua := gadget.ParseUA(`Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0`)

	fmt.Println(ua.String())  // "Firefox 73 on Windows 10"
	fmt.Println(ua.Browser()) // "Firefox 73"
	fmt.Println(ua.OS())      // "Windows 10"

	// Or for more detailed information:
	fmt.Println(ua.BrowserName)    // "Firefox"
	fmt.Println(ua.BrowserVersion) // "73"
	fmt.Println(ua.OSName)         // "Windows"
	fmt.Println(ua.OSVersion)      // "10"

	// Helper to shorten the UA string while remaining readable:
	uaHeader := `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4029.0 Safari/537.36`
	short := gadget.ShortenUA(uaHeader)
	fmt.Println(short)                                 // ~Z (~W NT 10.0; Win64; x64) ~a537.36 ~G ~c81.0.4029.0 ~s537.36
	fmt.Println(gadget.UnshortenUA(short) == uaHeader) // true

}

Output:

Firefox 73 on Windows 10
Firefox 73
Windows 10
Firefox
73
Windows
10
~Z (~W NT 10.0; Win64; x64) ~a537.36 ~G ~c81.0.4029.0 ~s537.36
true

func (UserAgent) Browser

func (u UserAgent) Browser() string

Browser gets the full browser, including the version (if any).

func (UserAgent) OS

func (u UserAgent) OS() string

OS gets the full operating system, including the version (if any).

func (UserAgent) String

func (u UserAgent) String() string

String shows the full Browser and OS name as "<browser> on <os>". If either one is blank the "on" will be omitted.

Source Files

gadget.go ua.go

Version
v1.0.0 (latest)
Published
Apr 17, 2022
Platform
linux/amd64
Imports
3 packages
Last checked
9 hours ago

Tools for package owners.