我分享了一个如何快速学习新语言的直播,但那是从实现一个后端框架的角度。理想通行证,还得从实际需求出发。一个小需求可能会遇到很多问题,但是搜索相关关键词可以快速实现,达到事半功倍的小目标。死记硬背手册太无聊了。反正受不了,还不如直接来个小项目。开始吧:一个小需求pc,mobile,一个地址有两套页面,需要根据浏览器的user_agent在后端展示不同的页面。通过php当然可以,但是活动页面的访问量一般比较大,想优化一下,所以想试试lua。在nginx中安装lua-nginx-module可以直接连接openresty,但是有时候就是想折腾一下。安装步骤https://mengkang.net/994.html(想练的再看一遍)luademo脚本--判断是否是手机浏览器函数isMobile(userAgent)--99%前三可以匹配上吧localmobile={"phone","android","mobile","itouch","ipod","symbian","htc","palmos","blackberry","operamini","windowsce”、“nokia”、“fennec”、“hiptop”、“kindle”、“mot”、“webos”、“samsung”、“sonyericsson”、“wap”、“avantgo”、“eudoraweb”、“minimo”","netfront","teleca"}userAgent=string.lower(userAgent)fori,vinipairs(mobile)doifstring.match(userAgent,v)thenreturntrueendendreturnfalseend--根据id+浏览器类型展示活动页面函数showPromotionHtml(id,isMobile)localpath="/data/www/mengkang/demo/promotion/"localfilenameifisMobilethenpath=path.."mobile"elsepath=path.."pc"endfilename=path.."/"..id..".html"iffile_exists(filename)thenlocalfile=io.open(filename,"r")io.input(file)print(io.read("*a"))io.close(file)elseprint("文件不存在:"..string.gsub(filename,"/data/www/mengkang/demo",""))endend--判断文件是否存在functionfile_exists(path)localfile=io.open(path,"rb")iffilethenfile:close()endreturnfile~=nilendlocalid=1localuserAgent="Mozilla/5.0(Macintosh;IntelMacOSX10_11_6)AppleWebKit/537.36(KHTML,likeGecko)Chrome/61.0.3163.79Safari/537.36"showPromotionHtml(id,isMobile(userAgent))总结作为一个lua菜鸟,我查了哪些资料本次小请求变量定义、函数编写、循环理解、判断逻辑编写、注释编写、文件i/o字符串拼接..字符串搜索字符串.匹配字符串为小写字符串.lower略微调整适配nginxlua模块——判断是否是手机浏览器函数isMobile(userAgent)--前三个99%都可以匹配本地mobile={"phone","android","mobile","itouch","ipod","symbian","htc","棕榈","blackberry","operamini","windowsce","nokia","fennec","hiptop","kindle","mot","webos","samsung","sonyericsson","wap","avantgo","eudoraweb","minimo","netfront","teleca"}userAgent=string.lower(userAgent)fori,vinipairs(mobile)doifstring.match(userAgent,v)thenreturntrueendendreturnfalseend--根据id+浏览器类展示活动页面functionshowPromotionHtml(id,isMobile)localpath="/data/www/mengkang/demo/promotion/"localfilenameifisMobilethenpath=path.."mobile"elsepath=path.."pc"endfilename=path.."/"..id..".html"iffile_exists(filename)thenlocalfile=io.open(filename,"r")io.input(file)ngx.say(io.read("*a"))io.close(file)elsengx.say("filenotfound:"..string.gsub(filename,"/data/www/mengkang/demo",""))endend--判断文件是否存在于functionfile_exists(path)localfile=io.open(path,"rb")iffilethenfile:close()endreturnfile~=nilendlocalid=ngx.var.idlocaluserAgent=ngx.req.get_headers().user_agentshowPromotionHtml(id,isMobile(userAgent))nginx配置服务器{听80;server_namemengkang.netlocation~/promotion/(\d+){set$id$1;默认类型“文本/html”;content_by_lua_file/data/www/lua/1.lua;}}demo地址https://mengkang.net/promotion/1https://mengkang.net/promotio...可以看到通过切换user_agent,不同pc和mobile版本的页面和php性能对比nginx配置重写^/promotion2/(.*)$/demo/promotion.phplast;phpcode
