Golang Gin 判断网页请求是否来自移动端

发布时间: 2020-02-16 17:40:49 作者: 大象笔记

由于我想对 PC 端和移动端展示不同的广告,需要判断网页请求是否来自移动端。

Golang Gin 中并没有找到内置的实现,我决定参考 wordpress PHP 代码中的实现,用 golang 实现一下。

参考:wordpress 判断是否为移动端浏览器的实现

对应的 Golang 实现

func IsMobile(userAgent string) bool {
	if len(userAgent) == 0 {
		return false
	}

	isMobile := false
	mobileKeywords := []string{"Mobile", "Android", "Silk/", "Kindle",
		"BlackBerry", "Opera Mini", "Opera Mobi"}

	for i := 0; i < len(mobileKeywords); i++ {
		if strings.Contains(userAgent, mobileKeywords[i]) {
			isMobile = true
			break
		}
	}

	return isMobile
}

func Index(c *gin.Context) {
	isMobile := utils.IsMobile(c.GetHeader("User-Agent"))
	// do something ...
}

Golang Template 中进行条件展示

{{ if .isMobile }}
  Mobile
{{ else }}
  PC
{{ end }}
我是一名山东烟台的开发者,联系作者