forked from x-dr/short
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 66ef7fc
Showing
11 changed files
with
801 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
# Logs | ||
logs | ||
*.log | ||
npm-debug.log* | ||
yarn-debug.log* | ||
yarn-error.log* | ||
lerna-debug.log* | ||
.pnpm-debug.log* | ||
|
||
# Diagnostic reports (https://nodejs.org/api/report.html) | ||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json | ||
|
||
# Runtime data | ||
pids | ||
*.pid | ||
*.seed | ||
*.pid.lock | ||
|
||
# Directory for instrumented libs generated by jscoverage/JSCover | ||
lib-cov | ||
|
||
# Coverage directory used by tools like istanbul | ||
coverage | ||
*.lcov | ||
|
||
# nyc test coverage | ||
.nyc_output | ||
|
||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) | ||
.grunt | ||
|
||
# Bower dependency directory (https://bower.io/) | ||
bower_components | ||
|
||
# node-waf configuration | ||
.lock-wscript | ||
|
||
# Compiled binary addons (https://nodejs.org/api/addons.html) | ||
build/Release | ||
|
||
# Dependency directories | ||
node_modules/ | ||
jspm_packages/ | ||
|
||
# Snowpack dependency directory (https://snowpack.dev/) | ||
web_modules/ | ||
|
||
# TypeScript cache | ||
*.tsbuildinfo | ||
|
||
# Optional npm cache directory | ||
.npm | ||
|
||
# Optional eslint cache | ||
.eslintcache | ||
|
||
# Optional stylelint cache | ||
.stylelintcache | ||
|
||
# Microbundle cache | ||
.rpt2_cache/ | ||
.rts2_cache_cjs/ | ||
.rts2_cache_es/ | ||
.rts2_cache_umd/ | ||
|
||
# Optional REPL history | ||
.node_repl_history | ||
|
||
# Output of 'npm pack' | ||
*.tgz | ||
|
||
# Yarn Integrity file | ||
.yarn-integrity | ||
|
||
# dotenv environment variable files | ||
.env | ||
.env.development.local | ||
.env.test.local | ||
.env.production.local | ||
.env.local | ||
|
||
# parcel-bundler cache (https://parceljs.org/) | ||
.cache | ||
.parcel-cache | ||
|
||
# Next.js build output | ||
.next | ||
out | ||
|
||
# Nuxt.js build / generate output | ||
.nuxt | ||
dist | ||
|
||
# Gatsby files | ||
.cache/ | ||
# Comment in the public line in if your project uses Gatsby and not Next.js | ||
# https://nextjs.org/blog/next-9-1#public-directory-support | ||
# public | ||
|
||
# vuepress build output | ||
.vuepress/dist | ||
|
||
# vuepress v2.x temp and cache directory | ||
.temp | ||
.cache | ||
|
||
# Docusaurus cache and generated files | ||
.docusaurus | ||
|
||
# Serverless directories | ||
.serverless/ | ||
|
||
# FuseBox cache | ||
.fusebox/ | ||
|
||
# DynamoDB Local files | ||
.dynamodb/ | ||
|
||
# TernJS port file | ||
.tern-port | ||
|
||
# Stores VSCode versions used for testing VSCode extensions | ||
.vscode-test | ||
|
||
# yarn v2 | ||
.yarn/cache | ||
.yarn/unplugged | ||
.yarn/build-state.yml | ||
.yarn/install-state.gz | ||
.pnp.* | ||
|
||
|
||
wrangler.toml | ||
|
||
.wrangler/* | ||
|
||
.wrangler |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2023 x-dr | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
## 介绍 | ||
|
||
一个使用 Cloudflare Pages 创建的 URL 缩短器 | ||
|
||
*Demo* : [https://d.131213.xyz/](https://d.131213.xyz/) | ||
|
||
|
||
|
||
### 利用Cloudflare pages部署 | ||
|
||
|
||
1. fork本项目 | ||
2. 登录到[Cloudflare](https://dash.cloudflare.com/)控制台. | ||
3. 在帐户主页中,选择`pages`> ` Create a project` > `Connect to Git` | ||
4. 选择你创建的项目存储库,在`Set up builds and deployments`部分中,全部默认即可。 | ||
5. 点击`Save and Deploy`,稍等片刻,你的网站就部署好了。 | ||
6. 创建D1数据库参考[这里](https://github.com/x-dr/telegraph-Image/blob/main/docs/manage.md) | ||
7. 执行sql命令创建表(在控制台输入框粘贴下面语句执行即可) | ||
|
||
```sql | ||
DROP TABLE IF EXISTS links; | ||
CREATE TABLE IF NOT EXISTS links ( | ||
`id` integer PRIMARY KEY NOT NULL, | ||
`url` text, | ||
`slug` text, | ||
`ua` text, | ||
`ip` text, | ||
`status` int, | ||
`create_time` DATE | ||
); | ||
DROP TABLE IF EXISTS logs; | ||
CREATE TABLE IF NOT EXISTS logs ( | ||
`id` integer PRIMARY KEY NOT NULL, | ||
`url` text , | ||
`slug` text, | ||
`referer` text, | ||
`ua` text , | ||
`ip` text , | ||
`create_time` DATE | ||
); | ||
|
||
``` | ||
8. 选择部署完成short项目,前往后台依次点击`设置`->`函数`->`D1 数据库绑定`->`编辑绑定`->变量名称填写:`DB` 命名空间 `选择你提前创建好的D1` 数据库绑定 | ||
|
||
|
||
### API | ||
|
||
#### 短链生成 | ||
|
||
```bash | ||
# POST /create | ||
curl -X POST -H "Content-Type: application/json" -d '{"url":"https://131213.xyz"}' https://d.131213.xyz/create | ||
|
||
# 指定slug | ||
curl -X POST -H "Content-Type: application/json" -d '{"url":"https://131213.xyz","slug":"scxs"}' https://d.131213.xyz/create | ||
|
||
``` | ||
|
||
|
||
|
||
> response: | ||
```json | ||
{ | ||
"slug": "<slug>", | ||
"link": "http://d.131213.xyz/<slug>" | ||
} | ||
``` | ||
|
||
|
||
|
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/** | ||
* @param {string} slug | ||
*/ | ||
|
||
export async function onRequestGet(context) { | ||
const { request, env, params } = context; | ||
// const url = new URL(request.url); | ||
const clientIP = request.headers.get("x-forwarded-for") || request.headers.get("clientIP"); | ||
const userAgent = request.headers.get("user-agent"); | ||
const Referer = request.headers.get('Referer') || "Referer" | ||
const originurl = new URL(request.url); | ||
const options = { | ||
timeZone: 'Asia/Shanghai', | ||
year: 'numeric', | ||
month: 'long', | ||
day: 'numeric', | ||
hour12: false, | ||
hour: '2-digit', | ||
minute: '2-digit', | ||
second: '2-digit' | ||
}; | ||
const timedata = new Date(); | ||
const formattedDate = new Intl.DateTimeFormat('zh-CN', options).format(timedata); | ||
|
||
const slug = params.id; | ||
|
||
const Url = await env.DB.prepare(`SELECT url FROM links where slug = '${slug}'`).first() | ||
|
||
if (!Url) { | ||
return Response.status(404).json({ message: 'Not Found.' }) | ||
} else { | ||
try { | ||
const info = await env.DB.prepare(`INSERT INTO logs (url, slug, ip,referer, ua, create_time) | ||
VALUES ('${Url.url}', '${originurl}', '${clientIP}','${Referer}', '${userAgent}', '${formattedDate}')`).run() | ||
// console.log(info); | ||
return Response.redirect(Url.url, 302); | ||
|
||
} catch (error) { | ||
console.log(error); | ||
return Response.redirect(Url.url, 302); | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
/** | ||
* @api {post} /create Create | ||
*/ | ||
|
||
// Path: functions/create.js | ||
|
||
function generateRandomString(length) { | ||
const characters = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | ||
let result = ''; | ||
|
||
for (let i = 0; i < length; i++) { | ||
const randomIndex = Math.floor(Math.random() * characters.length); | ||
result += characters.charAt(randomIndex); | ||
} | ||
|
||
return result; | ||
} | ||
export async function onRequestPost(context) { | ||
const { request, env } = context; | ||
const originurl = new URL(request.url); | ||
const clientIP = request.headers.get("x-forwarded-for") || request.headers.get("clientIP"); | ||
const userAgent = request.headers.get("user-agent"); | ||
const origin = `${originurl.protocol}://${originurl.hostname}` | ||
|
||
const options = { | ||
timeZone: 'Asia/Shanghai', | ||
year: 'numeric', | ||
month: 'long', | ||
day: 'numeric', | ||
hour12: false, | ||
hour: '2-digit', | ||
minute: '2-digit', | ||
second: '2-digit' | ||
}; | ||
const timedata = new Date(); | ||
const formattedDate = new Intl.DateTimeFormat('zh-CN', options).format(timedata); | ||
const { url, slug } = await request.json(); | ||
|
||
if (!url) return Response.json({ message: 'Missing required parameter: url.' }); | ||
|
||
// url格式检查 | ||
if (!/^https?:\/\/.{3,}/.test(url)) { | ||
return Response.json({ message: 'Illegal format: url.' }) | ||
} | ||
|
||
// 自定义slug长度检查 2<slug<10 | ||
if (slug && (slug.length < 2 || slug.length > 10)) { | ||
return Response.json({ message: 'Illegal length: slug, (>= 2 && <= 10).' }) | ||
} | ||
|
||
try { | ||
|
||
// 如果自定义slug | ||
if (slug) { | ||
const existUrl = await env.DB.prepare(`SELECT url as existUrl FROM links where slug = '${slug}'`).first() | ||
|
||
// url & slug 是一样的。 | ||
if (existUrl && existUrl.existUrl === url) { | ||
return Response.json({ slug, link: `${origin}/${slug2}` }) | ||
} | ||
|
||
// slug 已存在 | ||
if (existUrl) { | ||
return Response.json({ message: 'Slug already exists.' }) | ||
} | ||
} | ||
|
||
// 目标 url 已存在 | ||
const existSlug = await env.DB.prepare(`SELECT slug as existSlug FROM links where url = '${url}'`).first() | ||
|
||
// url 存在且没有自定义 slug | ||
if (existSlug && !slug) { | ||
return Response.json({ slug: existSlug.existSlug, link: `${origin}/${existSlug.existSlug}` }) | ||
} | ||
const slug2 = slug ? slug : generateRandomString(4); | ||
console.log('slug', slug2); | ||
|
||
const info = await env.DB.prepare(`INSERT INTO links (url, slug, ip, status, ua, create_time) | ||
VALUES ('${url}', '${slug2}', '${clientIP}',1, '${userAgent}', '${formattedDate}')`).run() | ||
|
||
return Response.json({ slug: slug2, link: `${origin}/${slug2}` }) | ||
} catch (e) { | ||
// console.log(e); | ||
return Response.json({ message: e.message }) | ||
} | ||
|
||
|
||
|
||
} | ||
|
||
|
||
|
Oops, something went wrong.