news 2026/4/18 2:01:18

go gin userAgent如何解析是手机还是PC

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
go gin userAgent如何解析是手机还是PC

在 Gin 框架中解析 User-Agent 判断设备类型,可以通过手动解析第三方库实现,推荐结合Gin 中间件使用。以下是具体方案:

一、手动解析(零依赖)

直接在 Gin 处理器中检查 User-Agent 字符串,适合简单场景:

go

复制

package main import ( "net/http" "strings" "github.com/gin-gonic/gin" ) // IsMobile 判断是否为移动设备 func IsMobile(userAgent string) bool { if userAgent == "" { return false } ua := strings.ToLower(userAgent) mobileKeywords := []string{ "mobile", "android", "iphone", "ipad", "ipod", "windows phone", "phone", "pad", "symbian", "blackberry", "nokia", "samsung", "htc", } for _, keyword := range mobileKeywords { if strings.Contains(ua, keyword) { return true } } return false } func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { userAgent := c.GetHeader("User-Agent") deviceType := "PC端" if IsMobile(userAgent) { deviceType = "移动端" } c.JSON(http.StatusOK, gin.H{ "user_agent": userAgent, "device_type": deviceType, }) }) r.Run(":8080") }

二、使用第三方库(推荐)

1. 使用mileusna/useragent

安装:

bash

复制

go get github.com/mileusna/useragent

Gin 集成示例:

go

复制

package main import ( "net/http" "github.com/gin-gonic/gin" "github.com/mileusna/useragent" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { uaString := c.GetHeader("User-Agent") ua := useragent.Parse(uaString) c.JSON(http.StatusOK, gin.H{ "user_agent": uaString, "device": ua.Device, // PC / Phone / Tablet / Bot "os": ua.OS, "browser": ua.Name, "version": ua.Version, "mobile": ua.Device == "Phone" || ua.Device == "Tablet", }) }) r.Run(":8080") }

2. 使用mssola/useragent

安装:

bash

复制

go get github.com/mssola/useragent

Gin 集成示例:

go

复制

package main import ( "net/http" "github.com/gin-gonic/gin" "github.com/mssola/useragent" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { uaString := c.GetHeader("User-Agent") ua := useragent.New("") ua.Parse(uaString) c.JSON(http.StatusOK, gin.H{ "user_agent": uaString, "mobile": ua.Mobile(), "os": ua.OS(), "browser": ua.Name(), "version": ua.Version(), "device_type": func() string { if ua.Mobile() { return "移动端" } return "PC端" }(), }) }) r.Run(":8080") }

三、最佳实践:Gin 中间件模式

将设备类型判断逻辑封装为中间件,供全局或局部路由使用:

go

复制

package main import ( "net/http" "strings" "github.com/gin-gonic/gin" ) // DeviceType 设备类型常量 const ( DevicePC = "pc" DeviceMobile = "mobile" DeviceTablet = "tablet" ) // DeviceInfo 设备信息 type DeviceInfo struct { Type string UserAgent string } const deviceInfoKey = "_device_info" // DeviceMiddleware 设备检测中间件 func DeviceMiddleware() gin.HandlerFunc { return func(c *gin.Context) { userAgent := c.GetHeader("User-Agent") deviceType := detectDevice(userAgent) // 将设备信息存储到 Gin Context c.Set(deviceInfoKey, DeviceInfo{ Type: deviceType, UserAgent: userAgent, }) // 为模板渲染添加全局变量 c.Set("isMobile", deviceType == DeviceMobile) c.Set("isPC", deviceType == DevicePC) c.Next() } } // detectDevice 检测设备类型 func detectDevice(userAgent string) string { if userAgent == "" { return DevicePC } ua := strings.ToLower(userAgent) // 平板识别 tabletKeywords := []string{"ipad", "android pad", "tablet", "kindle"} for _, keyword := range tabletKeywords { if strings.Contains(ua, keyword) { return DeviceTablet } } // 手机识别 mobileKeywords := []string{ "mobile", "android", "iphone", "ipod", "windows phone", "phone", "symbian", "blackberry", "nokia", "htc", } for _, keyword := range mobileKeywords { if strings.Contains(ua, keyword) { return DeviceMobile } } return DevicePC } // GetDeviceInfo 从Context获取设备信息 func GetDeviceInfo(c *gin.Context) (DeviceInfo, bool) { info, exists := c.Get(deviceInfoKey) if !exists { return DeviceInfo{}, false } return info.(DeviceInfo), true } func main() { r := gin.Default() // 应用全局中间件 r.Use(DeviceMiddleware()) // 路由示例 r.GET("/", func(c *gin.Context) { deviceInfo, _ := GetDeviceInfo(c) c.JSON(http.StatusOK, gin.H{ "device_type": deviceInfo.Type, "user_agent": deviceInfo.UserAgent, "message": func() string { switch deviceInfo.Type { case DeviceMobile: return "您正在使用移动设备访问" case DeviceTablet: return "您正在使用平板设备访问" default: return "您正在使用PC访问" } }(), }) }) // 为移动端和PC端返回不同内容 r.GET("/home", func(c *gin.Context) { deviceInfo, _ := GetDeviceInfo(c) if deviceInfo.Type == DeviceMobile { c.String(http.StatusOK, "移动端首页") return } c.String(http.StatusOK, "PC端首页") }) r.Run(":8080") }

四、方案对比

表格

复制

方案优点缺点推荐场景
手动解析无依赖、性能最好准确率一般、需维护关键词简单项目、对性能要求极高
第三方库准确率高、功能完整增加依赖、性能略低复杂项目、需要详细设备信息
中间件模式代码复用、逻辑清晰轻微性能损耗所有 Gin 项目(最佳实践)

生产环境建议:使用第三方库 + 中间件组合,平衡准确性与开发效率。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/17 8:35:12

GESP认证C++编程真题解析 | P10723 [GESP202406 七级] 黑白翻转

​欢迎大家订阅我的专栏:算法题解:C与Python实现! 本专栏旨在帮助大家从基础到进阶 ,逐步提升编程能力,助力信息学竞赛备战! 专栏特色 1.经典算法练习:根据信息学竞赛大纲,精心挑选…

作者头像 李华
网站建设 2026/4/17 13:46:26

C#学习路径与应用领域全方位指南

C#学习路径与应用领域全方位指南 C#作为微软开发的现代编程语言,凭借其简洁的语法、强大的类型系统和广泛的生态系统,已成为全栈开发的理想选择。学习C#的最佳路径应当遵循"环境搭建-基础语法-面向对象编程-高级特性-实战项目-设计模式与架构-开源贡…

作者头像 李华
网站建设 2026/4/18 1:12:51

2025最新!9款AI论文平台测评:本科生毕业论文写作全攻略

2025最新!9款AI论文平台测评:本科生毕业论文写作全攻略 2025年AI论文平台测评:为何需要一份权威榜单? 随着人工智能技术的不断进步,越来越多的本科生开始借助AI工具辅助毕业论文写作。然而,面对市场上种类繁…

作者头像 李华
网站建设 2026/4/16 21:51:47

Product Hunt 每日热榜 | 2025-12-24

1. Super Agents by ClickUp 标语:标签、消息, 在日常工作流程中管理人工智能助手。 介绍:超级代理是你可以在几秒钟内启动的AI助手,它们能够在ClickUp中执行整个工作流程。任何人都可以创建超级代理,并可以提及、分…

作者头像 李华
网站建设 2026/4/12 22:48:27

2025必备10个降AI率工具测评榜单

2025必备10个降AI率工具测评榜单 2025年降AI率工具测评:为何需要专业榜单? 随着高校和科研机构对AIGC内容的识别能力不断提升,论文、报告甚至日常作业中的AI生成痕迹越来越容易被检测出来。对于本科生而言,如何在保证内容原创性的…

作者头像 李华