在go语言中如何判断用户代理是否为移动设备的示例
Go  /  管理员 发布于 3个月前   168
在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
路人 在
php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..博主 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 @ mashrdn 多切换几个节点测试,免费ssr是没那么稳..mashrdn 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 V2rayn免费节点添加上去了,youtobe无法打开网页,是怎么回事..张伟 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 3q!有用,不过免费节点隔天就要去git上复制新的导进去..博主 在
科学上网翻墙访问Google , 上外网神器佛跳墙VPN(永久免费)使用流程步骤中评论 该篇教程已不能用了,告知大家,免的老有老铁问我!..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号