🤖
Ai回答
短链接生成接口设计
基础接口
POST /api/shorten
请求参数
json
{
original_url: https://example.com/very/long/url/to/be/shortened,
custom_alias: optional_custom_name, // 可选
expiration: 20241231, // 可选,默认永久
password: secret123 // 可选,密码保护
}
成功响应
json
{
status: success,
short_url: https://short.ly/abc123,
original_url: https://example.com/very/long/url/to/be/shortened,
expiration: 20241231T00:00:00Z,
qr_code: data:image/png;base64,..、 // 可选,二维码图片
}
错误响应
json
{
status: error,
code: INVALID_URL,
message: 提供的URL格式无效
}
统计接口
GET /api/stats/{short_code}
成功响应
json
{
short_code: abc123,
original_url: https://example.com/very/long/url/to/be/shortened,
created_at: 20230101T12:00:00Z,
expires_at: 20241231T00:00:00Z,
total_clicks: 42,
last_accessed: 20230515T08:30:45Z,
referrers: {
direct: 15,
google.com: 10,
twitter.com: 17
}
}
实现建议
1、短码生成算法:
使用Base62编码自增ID
或使用哈希算法(MD5/SHA1)取前几位
2、数据库设计:
sql
CREATE TABLE short_links (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
short_code VARCHAR(10) UNIQUE,
original_url TEXT NOT NULL,
custom_alias VARCHAR(20),
user_id BIGINT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NULL,
password VARCHAR(100),
click_count INT DEFAULT 0
);
3、重定向处理:
GET /{short_code}
→ 302重定向到原始URL
4、安全考虑:
验证URL格式
防止滥用(速率限制)
敏感内容过滤
需要任何特定平台的实现细节(如Python/Node.js/Go等)吗?