主题
Docker Hub 镜像代理
js
export default {
async fetch(request) {
const url = new URL(request.url)
const workerHost = url.hostname
const registry = 'registry-1.docker.io'
const auth = 'https://auth.docker.io'
// 转发 Docker Hub 令牌请求
if (url.pathname === '/token') {
const tokenUrl = auth + url.pathname + url.search
return fetch(tokenUrl, {
headers: request.headers,
})
}
// 转发 Docker Hub Registry API 请求
url.hostname = registry
const headers = new Headers(request.headers)
headers.set('Host', registry)
const response = await fetch(url.toString(), {
method: request.method,
headers,
body: request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body,
})
const newHeaders = new Headers(response.headers)
// 将认证地址改写为当前 Worker
const www = newHeaders.get('Www-Authenticate')
if (www) {
newHeaders.set('Www-Authenticate', www.replace(auth, `https://${workerHost}`))
}
return new Response(response.body, {
status: response.status,
headers: newHeaders,
})
},
}