本文来源于阿里云-云栖社区,原文点击这里。
怎么快速学习一门新的语言呢?
如果你已经熟练掌握了一门语言,那么其他语言都是想通的。一个小小的需求,可能会遇到很多问题,但是搜索相关的关键字,就能快速实现出来,完成一个小目标,事半功倍。
死记硬背手册,太枯燥了,反正我是看不下去,不如直接来个小项目。
一个小需求
pc、mobile 一个地址有两套页面,需要在后端根据浏览器的 user_agent 来显示不同的页面。
通过 php 来做,当然可以,但是活动页面访问量一般都比较大,想优化些,所以想尝试下 lua。
nginx 安装 lua-nginx-module
可以直接上 openresty,不过有时候就是想折腾。
安装的步骤 http://click.aliyun.com/m/31035/ (如果你想实践的话再看吧)
lua demo 脚本
-- 判断是否是手机浏览器
function isMobile(userAgent)
-- 99% 前三个都能匹配上吧
local mobile = {
"phone", "android", "mobile", "itouch", "ipod", "symbian", "htc", "palmos", "blackberry", "opera mini", "windows ce", "nokia", "fennec",
"hiptop", "kindle", "mot", "webos", "samsung", "sonyericsson", "wap", "avantgo", "eudoraweb", "minimo", "netfront", "teleca"
}
userAgent = string.lower(userAgent)
for i, v in ipairs(mobile) do
if string.match(userAgent, v) then
return true
end
end
return false
end
-- 根据id + 浏览器类型展示活动页面
function showPromotionHtml(id, isMobile)
local path = "/data/www/mengkang/demo/promotion/"
local filename
if isMobile then
path = path .. "mobile"
else
path = path .. "pc"
end
filename = path .. "/" .. id .. ".html"
if file_exists(filename) then
local file = io.open(filename,"r")
io.input(file)
print(io.read("*a"))
io.close(file)
else
print("文件不存在: " .. string.gsub(filename, "/data/www/mengkang/demo", ""))
end
end
-- 判断文件是否存在
function file_exists(path)
local file = io.open(path, "rb")
if file then file:close() end
return file ~= nil
end
local id = 1
local userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36"
showPromotionHtml(id, isMobile(userAgent))
小结
作为一个 lua 菜鸟,通过这个小需求我查了哪些资料。