在go语言中如何判断用户代理是否为移动设备的示例
在go语言中检测你的访客使用哪些设备来访问你的网站/应用程序的功能越来越常规了。
一旦你能够检测到正确的设备,你就可以专门为这些设备定制用户体验或其他功能。
下面我们将创建一个函数来确定一个用户代理是否是移动设备(iPad、Android等)。
示例代码:
package main
import (
"fmt"
"net/http"
"strings"
)
func is_mobile(useragent string) bool {
// 以下列表取自
// https://github.com/bcit-ci/CodeIgniter/blob/develop/system/libraries/User_agent.php
mobiles := []string{"Mobile Explorer","Palm","Motorola","Nokia","Palm","Apple iPhone","iPad","Apple iPod Touch","Sony Ericsson","Sony Ericsson","BlackBerry","O2 Cocoon","Treo", "LG", "Amoi", "XDA", "MDA", "Vario", "HTC", "Samsung",
"Sharp", "Siemens", "Alcatel", "BenQ", "HP iPaq", "Motorola", "PlayStation Portable", "PlayStation 3", "PlayStation Vita", "Danger Hiptop", "NEC", "Panasonic", "Philips", "Sagem", "Sanyo", "SPV", "ZTE", "Sendo", "Nintendo DSi", "Nintendo
DS", "Nintendo 3DS", "Nintendo Wii", "Open Web", "OpenWeb", "Android", "Symbian", "SymbianOS", "Palm", "Symbian S60", "Windows CE", "Obigo", "Netfront Browser", "Openwave Browser", "Mobile Explorer", "Opera Mini", "Opera Mobile", "Firefox
Mobile", "Digital Paths", "AvantGo", "Xiino", "Novarra Transcoder", "Vodafone", "NTT DoCoMo", "O2", "mobile", "wireless", "j2me", "midp", "cldc", "up.link", "up.browser", "smartphone", "cellphone", "Generic Mobile"}
for _, device := range mobiles {
if strings.Index(useragent, device) > -1 {
return true
}
}
return false
}
func checkIfUserAgentIsAMobile(w http.ResponseWriter, r *http.Request) {
ua := r.Header.Get("User-Agent")
fmt.Printf("用户代理是 %s \n", ua)
w.Write([]byte("用户代理是 " + ua + "\n"))
result := "no"
if is_mobile(ua) {
result = "yes"
}
fmt.Printf("用户代理是一个移动: %v \n", is_mobile(ua))
w.Write([]byte("用户代理是一个移动:" + result + "\n"))
}
func main() {
http.HandleFunc("/", checkIfUserAgentIsAMobile)
http.ListenAndServe(":8080", nil)
}
输出:
来自iPad的访问:
用户代理是 Mozilla/5.0 (iPad; CPU OS 921 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.107 Mobile/13D15 Safari/601.1.46
用户代理是一个移动:yes
来自Mac的:
用户代理是 Mozilla/5.0 (Macintosh; Intel Mac OS X 1085) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
用户代理是一个移动:no
相关文章:
在go语言中实现一个函数来检查用户代理是否是机器人或爬虫的示例
https://www.zongscan.com/demo333/96371.html
相关文章