This article is from the Aliyun-Yunqi community, click on the original article Here.
How to learn a new language quickly?
If you have mastered a language, all other languages are well thought out. A small need, may encounter many problems, but search for relevant keywords, can quickly achieve a small goal, twice the result with half the effort.
It's too boring to memorize manuals by rote. I can't read them anymore. I'd better go straight to a small project.
A small need
There are two sets of pages in an address of pc and mobile, and different pages need to be displayed in the back end according to the user_agent of the browser.
It can be done through php, of course, but the amount of active page visits is generally large, want to optimize some, so want to try lua.
Nginx installation lua-nginx-module
You can go directly to openresty, but sometimes you just want to toss around.
Installation steps http://click.aliyun.com/m/31035/ (If you want to practice, look at it again.)
lua demo script
-- Determine whether it's a mobile browser or not?
function isMobile(userAgent)
-- 99% You can match the first three.
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
-- according to id + Browser Type Display Activity Page
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("file does not exist: " .. string.gsub(filename, "/data/www/mengkang/demo", ""))
end
end
-- Determine whether a file exists
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))
Summary
As a lua rookie, what information did I check through this small requirement?