用openresty和lua实现壁纸投票功能

news2025/2/22 8:15:40

背景

之前做了一个随机壁纸接口,但是不知道大家喜欢对壁纸的喜好,所以干脆在实现一个投票功能,让用户给自己喜欢的壁纸进行投票。

原理说明

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) do
        if file ~= "." and file ~= ".." then
            local full_path = path .. "/" .. file
            local attr = lfs.attributes(full_path)
            if attr.mode == "file" and (file:match("%.jpg$") or file:match("%.png$")) then
                table.insert(images, file)
            elseif attr.mode == "directory" then
                local sub_images = get_images(full_path)
                for _, sub_image in ipairs(sub_images) do
                    table.insert(images, file .. "/" .. sub_image)
                end
            end
        end
    end
    return 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 then
        local content = file:read("*a")
        file:close()
        stats = cjson.decode(content) or {}
    end
    return stats
end

-- 保存统计结果
local function save_stats(stats)
    local stats_path = "/home/data/vote_stats.json"
    local file = io.open(stats_path, "w")
    if file then
        file:write(cjson.encode(stats))
        file:close()
    else
        ngx.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) do
        html = 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)
    end

    html = 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 then
        file:write(html)
        file:close()
    else
        ngx.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) do
        table.insert(sorted_stats, {img = img, count = data.count})
    end
    table.sort(sorted_stats, function(a, b)
        return a.count > b.count
    end)

    -- 生成 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) do
        if data.count > 0 then
            html = 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)
        end
    end

    html = 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 then
        file:write(html)
        file:close()
    else
        ngx.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 then
        ngx.log(ngx.ERR, "Failed to get POST args: ", err)
        ngx.exit(ngx.HTTP_BAD_REQUEST)
    end

    -- 获取投票人 IP
    local voter_ip = ngx.var.remote_addr

    -- 读取统计结果
    local stats = read_stats()

    -- 更新投票数据
    for img, _ in pairs(args) do
        if not stats[img] then
            stats[img] = {count = 0, voters = {}}
        end
        stats[img].count = stats[img].count + 1
    end

    -- 保存统计结果
    save_stats(stats)

    -- 生成 HTML 文件
    generate_vote_html()  -- 更新投票页面
    generate_result_html()  -- 生成投票结果页面

    -- 重定向到投票结果页面
    ngx.redirect("/vote/result.html")
end

-- 处理请求
if ngx.var.request_method == "POST" then
    handle_vote()
else
    generate_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/;
}

效果

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2301790.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

mysql查看binlog日志

mysql 配置、查看binlog日志&#xff1a; 示例为MySQL8.0 1、 检查binlog开启状态 SHOW VARIABLES LIKE ‘log_bin’; 如果未开启&#xff0c;修改配置my.ini 开启日志 安装目录配置my.ini(mysql8在data目录) log-binmysql-bin&#xff08;开启日志并指定日志前缀&#xff…

BiRefNet C++ TensorRT (二分类图像分割)

BiRefNet C TensorRT &#xff08;二分类图像分割&#xff09; 利用TensorRT和CUDA的双边参考网络&#xff08;BiRefNet&#xff09;的高性能c实现&#xff0c;针对实时高分辨率二分类图像分割进行了优化。 BiRefNet c TENSORRT旨在有效地在GPU上运行双边参考分割任务。通过利…

【ARM】MDK在编译 i.MXRT1芯片的时候出现报错Error: L6079E

1、 文档目标 解决MDK在编译 i.MXRT1芯片的时候出现报错Error: L6079E 2、 问题场景 客户在使用NXP 的NXP i.MXRT1050的芯片进行工程构建的时候出现下面的报错信息&#xff1a; Error: L6079E: Subtool invocation error: Error executing armcc. The system could not find…

论文笔记(七十二)Reward Centering(二)

Reward Centering&#xff08;二&#xff09; 文章概括摘要2 简单的奖励中心 文章概括 引用&#xff1a; article{naik2024reward,title{Reward Centering},author{Naik, Abhishek and Wan, Yi and Tomar, Manan and Sutton, Richard S},journal{arXiv preprint arXiv:2405.0…

推荐几款较好的开源成熟框架

一. 若依&#xff1a; 1. 官方网站&#xff1a;https://doc.ruoyi.vip/ruoyi/ 2. 若依SpringBootVueElement 的后台管理系统&#xff1a;https://gitee.com/y_project/RuoYi-Vue 3. 若依SpringBootVueElement 的后台管理系统&#xff1a;https://gitee.com/y_project/RuoYi-Cl…

基于知识图谱的问答系统:后端Python+Flask,数据库Neo4j,前端Vue3(提供源码)

基于知识图谱的问答系统&#xff1a;后端PythonFlask&#xff0c;数据库Neo4j&#xff0c;前端Vue3 引言 随着人工智能技术的不断发展&#xff0c;知识图谱作为一种结构化的知识表示方式&#xff0c;逐渐成为问答系统的重要组成部分。本文将介绍如何构建一个基于知识图谱的问答…

【华为机试】HJ80 整型数组合并

解法一&#xff1a; HashSet>List列表 Collections.sort(list)对列表进行排序 import java.util.*; import java.util.HashSet;// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main {public static void main(String[] args) {Scanner sc new Scanner(…

day17-后端Web原理——SpringBoot原理

目录 SpingBoot原理1. 配置优先级2. Bean管理2.1 获取Bean2.2 Bean作用域2.3 第三方Bean 3. SpringBoot原理3.1 起步依赖3.2 自动配置3.2.1 概述3.2.2 常见方案3.2.2.1 概述3.2.2.2 方案一3.2.2.3 方案二 3.2.3 原理分析3.2.3.1 源码跟踪3.2.3.2 Conditional 4. Web后端开发总结…

我们来学nginx -- work process

题记 工作进程能处理大量的并发请求几乎不会阻塞Worker进程可绑定到固定的核&#xff0c;避免CPU频繁地上下文切换看样子&#xff0c;还得转为人话 大白话 作为一般的应用的开发大部分人没有很强的底层技术基础如果深究&#xff0c;涉及复杂技术点&#xff0c;很容易迷惘为什…

【PLL】应用:同步

1. 用于时钟去偏移的PLL 时钟频率增加内部时钟与外部时钟的偏移&#xff0c;在芯片之间通信时很重要时钟偏移可能是由时钟树引起的&#xff0c;该时钟树缓冲外部时钟以驱动大量内部节点 芯片间通信中的时钟偏移问题 芯片1和芯片2共享外部时钟CKext芯片内部逻辑电路操作的实际时…

Go入门之数组与切片

var arr1 [...]int{1, 2, 3}fmt.Println(len(arr1)) 数组长度不能扩展 var arr2 [...]int{0: 100, 5: 101}fmt.Println(len(arr2)) } 指定索引初始化 可以通过for和range遍历 值类型:基本数据类型和数组都是值类型&#xff0c;改变副本的值不会改变本身的值 切片为引用数…

30天开发操作系统 第22天 -- 用C语言编写应用程序

前言 在昨天的最后我们成功干掉了crack2.hrb, 今天我们要尝试一下更厉害的攻击手段。 所以说, 从现在开始又要打开坏人模式了哟&#xff0c;嘿嘿嘿 虽然把操作系统的段地址存入DS这一招现在已经不能用了&#xff0c;不过我可不会善罢甘休的。我要想个更厉害的招数&#xff0c…

后端开发:开启技术世界的新大门

在互联网的广阔天地中&#xff0c;后端开发宛如一座大厦的基石&#xff0c;虽不直接与用户 “面对面” 交流&#xff0c;却默默地支撑着整个互联网产品的稳定运行。它是服务器端编程的核心领域&#xff0c;负责处理数据、执行业务逻辑以及与数据库和其他后端服务进行交互。在当…

20250220解决使用top指令查看荣品PRO-RK3566开发板的CPU占用率为400%的问题

20250220解决使用top指令查看荣品PRO-RK3566开发板的CPU占用率为400%的问题 2025/2/20 19:14 缘起&#xff0c;使用荣品PRO-RK3566开发板配套的百度网盘中的SDK&#xff1a;Android13编译之后&#xff0c;查看RK3566的CPU占用率为400%。 开机就是400%&#xff0c;什么时候都是4…

win32汇编环境,窗口程序中使用月历控件示例二

;运行效果 ;win32汇编环境,窗口程序中使用月历控件示例二 ;以下示例有2个操作,即将每周的开始日进行改变,将默认的周日开始改为周一开始,同时实现点击哪个日期,则设定为哪个日期 ;直接抄进RadAsm可编译运行。重要部分加备注。 ;下面为asm文件 ;>>>>>>>…

java毕业设计之医院门诊挂号系统(源码+文档)

风定落花生&#xff0c;歌声逐流水&#xff0c;大家好我是风歌&#xff0c;混迹在java圈的辛苦码农。今天要和大家聊的是一款基于ssm的医院门诊挂号系统。项目源码以及部署相关请联系风歌&#xff0c;文末附上联系信息 。 项目简介&#xff1a; 医院门诊挂号系统的主要使用者…

Linux 实操篇 组管理和权限管理、定时任务调度、Linux磁盘分区和挂载

一、组管理和权限管理 &#xff08;1&#xff09;Linux组基本介绍 在linux中的每个用户必须属于一个组&#xff0c;不能独立于组外 在linux中每个文件有所有者、所在组、其他组的概念 &#xff08;2&#xff09;文件/目录 所有者 一般为文件的创建者&#xff0c;谁创建了该…

MySql中的事务、MySql事务详解、MySql隔离级别

文章目录 一、什么是事务&#xff1f;二、事务四大特性ACID 2.1、原子性&#xff08;Atomicity&#xff09;2.2、一致性&#xff08;Consistency&#xff09;2.3、隔离性&#xff08;Isolation&#xff09;2.4、持久性&#xff08;Durability&#xff09; 三、事务操作/事务的…

10、k8s对外服务之ingress

service和ingress的作用 service的作用 NodePort&#xff1a;会在每个节点开放一个端口&#xff0c;端口号30000-32767。 也是只能用于内网访问&#xff0c;四层转发。实现负载均衡。不能基于域名进行访问。 clusterip&#xff1a;service的默认类型&#xff0c;只能在集群…

【STM32】舵机SG90

1.舵机原理 舵机内部有一个电位器&#xff0c;当转轴随电机旋转&#xff0c;电位器的电压会发生改变&#xff0c;电压会带动转一定的角度&#xff0c;舵机中的控制板就会电位器输出的电压所代表的角度&#xff0c;与输入的PWM所代表的角度进行比较&#xff0c;从而得出一个旋转…