Files
谢宇宁andClaude Opus 5.5 0fbdba5ccf Initial commit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:47:47 +07:00

97 lines
2.6 KiB
Go

package useragent
import (
"net/url"
"strings"
"videoweb/pub/common/enum/consts"
"videoweb/pub/common/log"
"github.com/gin-gonic/gin"
)
type UA struct {
DevID string
DevType string
SysType string
Ver string
BuildID string
}
func IsH5(sysType string) bool {
if sysType == consts.H5IOS || sysType == consts.H5Android || sysType == consts.H5PC || sysType == consts.H5 || sysType == consts.Light {
return true
} else {
return false
}
}
func (s UA) IsH5() bool {
return IsH5(s.SysType)
}
func UserAgent(c *gin.Context) {
var uastr string
ua := UA{}
userAgent := c.GetHeader("X-User-Agent") //兼容H5 UserAgent
if userAgent == "" {
userAgent = c.Request.UserAgent()
}
if userAgent != "" {
// "BuildID=com.abc.Butterfly;SysType=h5;DevID=B9A00938-FE68-4686-9461-A365C7E5110D;Ver=0.0.1;DevType=iPhone;"
decodeUa, err := url.QueryUnescape(userAgent)
if err != nil {
log.Warn("URLDecode user-agent error", log.Any("ua", userAgent))
uastr = userAgent
} else {
uastr = decodeUa
}
uas := strings.Split(uastr, ";")
for _, v := range uas {
vss := strings.Split(strings.TrimSpace(v), "=")
if len(vss) < 2 {
c.Set(consts.CtxUAH5, vss[0])
// log.Warn("user-agent miss", log.Any("ua", userAgent), log.Any("v", v))
continue
}
switch strings.TrimSpace(vss[0]) {
case "DevID":
ua.DevID = strings.TrimSpace(vss[1])
c.Set(consts.CtxDevId, ua.DevID)
case "DevType":
ua.DevType = strings.TrimSpace(vss[1])
c.Set(consts.CtxDevType, ua.DevType)
case "SysType":
IntputSysType := strings.TrimSpace(vss[1])
if strings.Contains(IntputSysType, "h5_android") {
ua.SysType = consts.H5Android
} else if strings.Contains(IntputSysType, "h5_ios") {
ua.SysType = consts.H5IOS
} else if strings.Contains(IntputSysType, "h5_pc") {
ua.SysType = consts.H5PC
} else if strings.Contains(IntputSysType, "android") {
ua.SysType = consts.Android
} else if strings.Contains(IntputSysType, "ios") {
ua.SysType = consts.IOS
} else if strings.Contains(IntputSysType, "h5") {
ua.SysType = consts.H5
} else if strings.Contains(IntputSysType, "pc") {
ua.SysType = consts.PC
} else if strings.Contains(IntputSysType, "light") {
ua.SysType = consts.Light
}
c.Set(consts.CtxSysType, ua.SysType)
case "Ver":
ua.Ver = strings.TrimSpace(vss[1])
c.Set(consts.CtxVersion, ua.Ver)
case "BuildID":
ua.BuildID = strings.TrimSpace(vss[1])
c.Set(consts.CtxBuildId, ua.BuildID)
default:
log.Warn("user-agent unknown", log.Any("ua", userAgent))
}
}
} else {
log.Warn("user-agent empty")
}
c.Set(consts.CtxUA, ua)
}