random支持返回完整url

This commit is contained in:
MarSeventh
2024-07-27 10:39:29 +08:00
parent 8bbe081dc5
commit 070a379b29
2 changed files with 22 additions and 8 deletions

View File

@@ -121,13 +121,13 @@ API格式
#### 随机图API
| 接口名称 | /random |
| ------------ | ---------------------------------------------------- |
| **接口功能** | 从图床中随机返回一张图片的链接(注意会消耗列出次数) |
| **前置条件** | 设置`AllowRandom`环境变量,值为`true` |
| **请求方法** | GET |
| **请求参数** | |
| **响应格式** | data.url为返回的链接。 |
| 接口名称 | /random |
| ------------ | ------------------------------------------------------------ |
| **接口功能** | 从图床中随机返回一张图片的链接(注意会消耗列出次数) |
| **前置条件** | 设置`AllowRandom`环境变量,值为`true` |
| **请求方法** | GET |
| **请求参数** | **Query参数**<br />`type`:设为`url`时返回完整url链接否则返回随机图的文件路径。 |
| **响应格式** | data.url为返回的链接/文件路径。 |
> **请求示例**
>

View File

@@ -8,6 +8,10 @@ export async function onRequest(context) {
next, // used for middleware or to fetch assets
data, // arbitrary space for passing data between middlewares
} = context;
const requestUrl = new URL(request.url);
const protocol = requestUrl.protocol;
const domain = requestUrl.hostname;
const port = requestUrl.port;
const list = await env.img_url.list();
if (env.AllowRandom != "true") {
return new Response(JSON.stringify({ error: "Random is disabled" }), { status: 403 });
@@ -17,7 +21,17 @@ export async function onRequest(context) {
} else {
const randomIndex = Math.floor(Math.random() * list.keys.length);
const randomKey = list.keys[randomIndex];
const randomUrl = '/file/' + randomKey.name;
const randomPath = '/file/' + randomKey.name;
let randomUrl = randomPath;
const randomType = requestUrl.searchParams.get('type');
// if param 'type' is set to 'url', return the full URL
if (randomType == 'url') {
if (port) {
randomUrl = protocol + '//' + domain + ':' + port + randomPath;
} else {
randomUrl = protocol + '//' + domain + randomPath;
}
}
return new Response(JSON.stringify({ url: randomUrl }), { status: 200 });
}
}