Skip to content

Instantly share code, notes, and snippets.

@bactisme
Created December 22, 2016 15:47
Show Gist options
  • Save bactisme/8ad60395a0336e22828cf74bfea96356 to your computer and use it in GitHub Desktop.
Save bactisme/8ad60395a0336e22828cf74bfea96356 to your computer and use it in GitHub Desktop.
Classify the result of UA-Parser
package main
/** This is a rewrite of the PHP ua-classifier in golang
* https://github.com/phlib/ua-classifier/blob/master/src/Classifier.php
*/
import (
"strings"
"github.com/ua-parser/uap-go/uaparser"
)
var mobileOSs = []string{"windows phone 6.5", "windows ce", "symbian os"}
var mobileBrowsers = []string{
"firefox mobile", "opera mobile", "opera mini",
"mobile safari", "webos", "ie mobile", "playstation portable", "nokia", "blackberry",
"palm", "silk", "android", "maemo", "obigo", "netfront", "avantgo", "teleca", "semc-browser",
"bolt", "iris", "up.browser", "symphony", "minimo", "bunjaloo", "jasmine", "dolfin", "polaris",
"brew", "chrome mobile", "uc browser", "tizen browser",
}
var tablets = []string{"kindle", "ipad", "playbook", "touchpad", "dell streak", "galaxy tab", "xoom"}
var mobileDevices = []string{
"iphone", "ipod", "ipad", "htc", "kindle", "lumia", "amoi", "asus", "bird", "dell",
"docomo", "huawei", "i-mate", "kyocera", "lenovo", "lg", "kin", "motorola", "philips",
"samsung", "softbank", "palm", "hp ", "generic feature phone", "generic smartphone",
}
type UAClassified struct {
MatchType string // 'device', 'os', 'ua'
IsTablet bool
IsMobileDevice bool
IsMobile bool
IsComputer bool
IsSpider bool
}
func stringInSlice(s string, slice []string) bool {
for _, a := range slice {
if a == s {
return true
}
}
return false
}
func ClassifyUA(client *uaparser.Client) UAClassified {
result := UAClassified{
MatchType: "",
IsMobileDevice: false,
IsMobile: false,
IsTablet: false,
IsSpider: false,
IsComputer: true,
}
family := strings.ToLower(client.Device.Family)
if stringInSlice(family, tablets) {
result.MatchType = "device"
result.IsTablet = true
result.IsMobileDevice = true
result.IsComputer = false
} else if stringInSlice(family, mobileDevices) {
result.MatchType = "device"
result.IsMobileDevice = true
result.IsMobile = true
result.IsComputer = false
} else if family == "spider" {
result.MatchType = "device"
result.IsSpider = true
result.IsComputer = false
} else if stringInSlice(family, mobileOSs) {
result.MatchType = "device"
result.IsMobileDevice = true
result.IsMobile = true
result.IsComputer = false
} else if stringInSlice(family, mobileBrowsers) {
result.MatchType = "device"
result.IsMobileDevice = true
result.IsMobile = true
result.IsComputer = false
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment