FC + OSS 镜像源中转处理

为什么要做自己的镜像呢?国外网络慢;国内更新慢或者可用性有时有问题,免费的就是这个世界上最昂贵的。

方案大概流程:

  1. OSS 配置回源到 FC 地址。
  2. FC 根据请求路径重定向到某镜像源。
  3. OSS 自动下载重定向后文件到存储桶(第一次访问会比较慢,因为要下载完文件后才能返回给用户)。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php

use RingCentral\Psr7\Response;

function handler($request, $context): Response{
$path = $request->getAttribute('path');

if(!$path) {
return error();
}

// CDNJS
if(strpos($path, '/ajax/libs/') === 0) {
// https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js
return location('https://cdnjs.cloudflare.com/' . substr($path, strlen('/ajax/libs/')));
}

// UNPKG
if(strpos($path, '/unpkg/') === 0) {
// https://unpkg.com/axios@0.20.0/dist/axios.min.js
return location('https://unpkg.com/' . substr($path, strlen('/unpkg/')));
}

// PHP
if(strpos($path, '/php/') === 0) {
// https://www.php.net/distributions/php-7.4.9.tar.gz
return location('https://www.php.net/distributions/' . substr($path, strlen('/software/php/')));
}

// Node.js
if(strpos($path, '/node/') === 0) {
// https://nodejs.org/dist/v14.9.0/node-v14.9.0-x64.msi
return location('https://nodejs.org/dist/' . substr($path, strlen('/software/node/')));
}

// Python
if(strpos($path, '/python/') === 0) {
// https://www.python.org/ftp/python/3.8.5/python-3.8.5.exe
return location('https://www.python.org/ftp/python/' . substr($path, strlen('/python/')));
}

return error();
}

function location(string $url): Response {
return new Response(301, [
'Location' => $url,
]);
}

function error(): Response {
return new Response(404, [
'Content-Type'=> 'application/json'
]);
}
往上