From 20f68416a7c5dc7dc10222d31f20ec0b8ec2b41a Mon Sep 17 00:00:00 2001 From: kataras Date: Mon, 4 Dec 2017 08:12:34 +0200 Subject: [PATCH] add context#IsMobile Former-commit-id: 2f857e2b57a10233d4c9ea5ec365b84c1b8b1c76 --- context/context.go | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/context/context.go b/context/context.go index b357f936..a669f619 100644 --- a/context/context.go +++ b/context/context.go @@ -382,7 +382,12 @@ type Context interface { // Read more at: https://developer.mozilla.org/en-US/docs/AJAX // and https://xhr.spec.whatwg.org/ IsAjax() bool - + // IsMobile checks if client is using a mobile device(phone or tablet) to communicate with this server. + // If the return value is true that means that the http client using a mobile + // device to communicate with the server, otherwise false. + // + // Keep note that this checks the "User-Agent" request header. + IsMobile() bool // +------------------------------------------------------------+ // | Response Headers helpers | // +------------------------------------------------------------+ @@ -1316,6 +1321,18 @@ func (ctx *context) IsAjax() bool { return ctx.GetHeader("X-Requested-With") == "XMLHttpRequest" } +var isMobileRegex = regexp.MustCompile(`(?i)(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)`) + +// IsMobile checks if client is using a mobile device(phone or tablet) to communicate with this server. +// If the return value is true that means that the http client using a mobile +// device to communicate with the server, otherwise false. +// +// Keep note that this checks the "User-Agent" request header. +func (ctx *context) IsMobile() bool { + s := ctx.GetHeader("User-Agent") + return isMobileRegex.MatchString(s) +} + // +------------------------------------------------------------+ // | Response Headers helpers | // +------------------------------------------------------------+