背景
之前做了一個隨機壁紙接口,但是不知道大家喜歡對壁紙的喜好,所以干脆在實現一個投票功能,讓用戶給自己喜歡的壁紙進行投票。
原理說明
1.當訪問http://demo.com/vote/
時,會從/home/jobs/webs/imgs
及子目錄下獲取圖片列表,然后生成一個投票的vote.html頁面,并自動跳轉到http://demo.com/vote/vote.html
,點擊圖片即可選中/取消選中,在右下角始終有個懸浮按鈕"投票"
2.當點擊"投票"之后,會POST調用http://demo.com/vote/
,把結果記錄到home/data/vote_stats.json
,里面記錄了得票的圖片路徑和票數。
3.之后會生成一個result.html頁面,并自動跳轉到http://demo.com/vote/result.html
,壁紙根據得票數自動排序,最下方有個"返回投票頁"的按鈕
實戰
創建vote目錄,存放vote.html和result.html
mkdir /home/jobs/webs/vote
chmod 755 /home/jobs/webs/vote -R
chown nginx:nginx /home/jobs/webs/vote -R
編寫lua腳本
cat /etc/nginx/conf.d/vote.lua
package.path = package.path .. ";/usr/local/share/lua/5.1/?.lua;/usr/share/lua/5.1/?.lua"
package.cpath = package.cpath .. ";/usr/local/lib/lua/5.1/?.so;/usr/lib64/lua/5.1/?.so"local cjson = require "cjson"
local lfs = require "lfs"-- 獲取圖片列表
local function get_images(path)local images = {}for file in lfs.dir(path) doif file ~= "." and file ~= ".." thenlocal full_path = path .. "/" .. filelocal attr = lfs.attributes(full_path)if attr.mode == "file" and (file:match("%.jpg$") or file:match("%.png$")) thentable.insert(images, file)elseif attr.mode == "directory" thenlocal sub_images = get_images(full_path)for _, sub_image in ipairs(sub_images) dotable.insert(images, file .. "/" .. sub_image)endendendendreturn images
end-- 讀取統計結果
local function read_stats()local stats_path = "/home/data/vote_stats.json"local stats = {}local file = io.open(stats_path, "r")if file thenlocal content = file:read("*a")file:close()stats = cjson.decode(content) or {}endreturn stats
end-- 保存統計結果
local function save_stats(stats)local stats_path = "/home/data/vote_stats.json"local file = io.open(stats_path, "w")if file thenfile:write(cjson.encode(stats))file:close()elsengx.log(ngx.ERR, "Failed to open file: ", stats_path)end
end-- 生成投票頁面 HTML
local function generate_vote_html()local images = get_images("/home/jobs/webs/imgs")-- 生成 HTML 內容local html = [[<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>壁紙投票</title><style>body { font-family: Arial, sans-serif; }img { width: 200px; margin: 10px; border: 3px solid transparent; cursor: pointer; }img.selected { border: 3px solid #007bff; }.image-container { display: flex; flex-wrap: wrap; }.image-item { margin: 10px; text-align: center; }.floating-button {position: fixed;bottom: 20px;right: 20px;padding: 10px 20px;background-color: #007bff;color: white;border: none;border-radius: 5px;cursor: pointer;}.floating-button:hover {background-color: #0056b3;}</style><script>function toggleSelection(img) {img.classList.toggle("selected");var checkbox = img.parentElement.querySelector('input[type="checkbox"]');checkbox.checked = !checkbox.checked;}</script></head><body><h1>壁紙投票</h1><form method="post" action="/vote/"><div class="image-container">]]-- 添加圖片和復選框for _, img in ipairs(images) dohtml = html .. string.format([[<div class="image-item"><input type="checkbox" name="%s" id="%s" style="display: none;"><label for="%s"><img src="/vote/imgs/%s" alt="%s" onclick="toggleSelection(this)"></label></div>]], img, img, img, img, img)endhtml = html .. [[</div><button type="submit" class="floating-button">提交投票</button></form></body></html>]]-- 將 HTML 內容寫入文件local html_file_path = "/home/jobs/webs/vote/vote.html"local file = io.open(html_file_path, "w")if file thenfile:write(html)file:close()elsengx.log(ngx.ERR, "Failed to open file: ", html_file_path)end
end-- 生成投票結果頁面 HTML
local function generate_result_html()local stats = read_stats()-- 按票數排序local sorted_stats = {}for img, data in pairs(stats) dotable.insert(sorted_stats, {img = img, count = data.count})endtable.sort(sorted_stats, function(a, b)return a.count > b.countend)-- 生成 HTML 內容local html = [[<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>投票結果</title><style>body { font-family: Arial, sans-serif; }.stats { margin-top: 20px; }img { width: 200px; margin: 10px; border: 1px solid #ccc; }.image-container { display: flex; flex-wrap: wrap; }.image-item { margin: 10px; text-align: center; }</style></head><body><h1>投票結果</h1><div class="image-container">]]-- 顯示投票結果for _, data in ipairs(sorted_stats) doif data.count > 0 thenhtml = html .. string.format([[<div class="image-item"><img src="/vote/imgs/%s" alt="%s"><p>%s: %d 票</p></div>]], data.img, data.img, data.img, data.count)endendhtml = html .. [[</div><a href="/vote/vote.html">返回投票頁面</a></body></html>]]-- 將 HTML 內容寫入文件local result_file_path = "/home/jobs/webs/vote/result.html"local file = io.open(result_file_path, "w")if file thenfile:write(html)file:close()elsengx.log(ngx.ERR, "Failed to open file: ", result_file_path)end
end-- 處理投票
local function handle_vote()-- 確保請求體已讀取ngx.req.read_body()-- 獲取 POST 參數local args, err = ngx.req.get_post_args()if not args thenngx.log(ngx.ERR, "Failed to get POST args: ", err)ngx.exit(ngx.HTTP_BAD_REQUEST)end-- 獲取投票人 IPlocal voter_ip = ngx.var.remote_addr-- 讀取統計結果local stats = read_stats()-- 更新投票數據for img, _ in pairs(args) doif not stats[img] thenstats[img] = {count = 0, voters = {}}endstats[img].count = stats[img].count + 1end-- 保存統計結果save_stats(stats)-- 生成 HTML 文件generate_vote_html() -- 更新投票頁面generate_result_html() -- 生成投票結果頁面-- 重定向到投票結果頁面ngx.redirect("/vote/result.html")
end-- 處理請求
if ngx.var.request_method == "POST" thenhandle_vote()
elsegenerate_vote_html() -- 生成投票頁面ngx.redirect("/vote/vote.html") -- 重定向到投票頁面
end
對應的openresty配置
location /vote/vote.html {try_files /vote/vote.html =404;
}
location /vote/result.html {try_files /vote/result.html =404;
}location /vote/ {lua_need_request_body on; # 啟用請求體讀取 content_by_lua_file /etc/nginx/conf.d/vote.lua;
}
# 靜態圖片服務,用于展示壁紙
location /vote/imgs/ {alias /home/jobs/webs/imgs/;
}