在go语言中如何判断用户代理是否为移动设备的示例
Go  /  管理员 发布于 2年前   664
在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
test1 在
opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..Zita 在
Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
