Back to godoc.org
zgo.at/gadget

package gadget

v0.0.0 (6441213)
Latest Go to latest
Published: May 22, 2020 | License: MIT | Module: zgo.at/gadget

Index

Examples

func Shorten

func Shorten(ua string) string

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

Use Unshorten() 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 Unshorten

func Unshorten(short string) string

Unshorten reverses Shorten().

type UserAgent

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

func Parse

func Parse(uaHeader string) UserAgent

Parse a User-Agent header.

Example

Code:

ua := gadget.Parse(`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.Shorten(uaHeader)
fmt.Println(short)                               // ~Z (~W NT 10.0; Win64; x64) ~a537.36 ~G ~c81.0.4029.0 ~s537.36
fmt.Println(gadget.Unshorten(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.

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
f or F : Jump to identifier