lua-resty-shortlink

"一个用于将给定长 URL 生成动态短 URL 的 Lua 模块"

$ opm get iakuf/lua-resty-shortlink

OpenResty 的 Lua 短链接服务

此 Lua 模块为 OpenResty 提供 URL 短链接服务,并与 Redis 集成以进行存储。它通过允许动态配置目标重定向域来提供灵活且可重用的解决方案。

功能

  • 短 URL 创建: 为给定的长 URL 生成短 URL,并将其存储在 Redis 中。

  • 重定向服务: 将短 URL 重定向到其对应的长 URL,并使用 302 HTTP 状态代码。

  • 自动重复检测: 如果提交相同的长 URL,则返回现有的短 URL。

  • 可配置域: 可以通过模块的初始化动态配置重定向域。

要求

  • OpenResty

  • Redis

  • LuaJIT

安装

要安装此模块,您可以使用 OpenResty 包管理器 (opm)

    opm get iakuf/lua-resty-shortlink

配置

在您的 nginx.conf

    http {
        
        init_by_lua_block {
            local shortlink = require "resty.shortlink"
            shortlink.init({
                host = "127.0.0.1",
                port = 6379,
                timeout = 1000,
                domain = "http://yourdomain.com"  -- Set your desired redirection domain here
            })
        }
    
        server {
            listen 80;
    
            location /create {
                content_by_lua_block {
                    local shortlink = require "resty.shortlink"
                    shortlink.create()
                }
            }
    
            location /s/ {
                content_by_lua_block {
                    local shortlink = require "resty.shortlink"
                    shortlink.redirect()
                }
            }
        }
    }

配置选项

  • host: Redis 服务器主机名 (默认值: 127.0.0.1)

  • port: Redis 服务器端口 (默认值: 6379)

  • timeout: Redis 连接超时时间(以毫秒为单位)(默认值: 1000)

  • domain: 用于生成短链接的域 (默认值: "http://yourdomain.com")

API 端点

POST /create

创建一个新的短 URL。

请求主体

    {
        "url": "http://example.com/very/long/url",
        "expiry": 3600  // Expiry time in seconds
    }

响应

    {
        "short_link": "http://yourdomain.com/s/abc123"
    }
  • 如果 URL 已经缩短,则返回现有的短链接。

重定向到与提供的短链接关联的原始 URL。

  • 例如: 访问 http://yourdomain.com/s/abc123 将重定向到 http://example.com/very/long/url

示例用法

您可以使用 curl 测试服务

    curl -X POST http://localhost:8080/create -d '{"url": "http://example.com", "expiry": 3600}'
    curl -i http://localhost:8080/s/abc123

许可证

此项目是在 MIT 许可证下授权的 - 有关详细信息,请参阅 LICENSE 文件。

贡献

欢迎贡献!请分叉仓库并提交拉取请求。

致谢

  • 使用 OpenRestyRedis 构建。

  • 受对高效且可扩展的 URL 短链接服务需求的启发。

作者

"Fu Kai <iakuf@163.com>"

许可证

mit

版本