Skip to content

Commit

Permalink
fix: incorrect status code for cf-worker proxy(reruin#347)
Browse files Browse the repository at this point in the history
  • Loading branch information
reruin committed Dec 25, 2020
1 parent c1c1248 commit 511f76a
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions proxy/cf-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const utils = {
end = end ? parseInt(end) : total - 1
return [start, end]
},
parserHeaders(headers) {
parseHeaders(headers) {
let ret = {}
for (let pair of headers.entries()) {
ret[pair[0].toLowerCase()] = pair[1]
Expand All @@ -33,8 +33,8 @@ const utils = {
let response = await fetch(url, { method: 'GET' })
return await response.json()
},
notfound() {
return new Response('404 Not found', { status: 404 })
notfound(e) {
return new Response(e || '404 Not found', { status: 404 })
}
}

Expand All @@ -44,7 +44,7 @@ async function handleRequest({ headers, method, url }) {

if (pathname == '/') return utils.notfound()

let reqHeaders = utils.parserHeaders(headers)
let reqHeaders = utils.parseHeaders(headers)
let mergeHeaders = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
Expand All @@ -65,23 +65,21 @@ async function handleRequest({ headers, method, url }) {
let [start, end] = utils.getRange(reqHeaders.range, size)
resHeaders['content-range'] = `bytes ${start}-${end}/${size}`
size = end - start + 1
} else {
resHeaders['content-range'] = `bytes 0-${size-1}/${size}`
status = 206
}
status = 206

resHeaders['content-length'] = size
}

let extraHeaders = resp.headers || {}
let output = fetch(url, { method: 'GET', headers: { ...mergeHeaders, ...reqHeaders, ...extraHeaders } })
return output.then(r => new Response(r.body, {
return fetch(url, { method: 'GET', headers: { ...mergeHeaders, ...reqHeaders, ...extraHeaders } }).then(r => new Response(r.body, {
status: status,
headers: { ...utils.parserHeaders(r.headers), ...resHeaders }
headers: { ...utils.parseHeaders(r.headers), ...resHeaders }
}))
} else {
return utils.notfound()
}
}

addEventListener('fetch', event => event.respondWith(handleRequest(new Request(event.request))
.catch(e => utils.notfound())))
.catch(e => utils.notfound(e.toString()))))

0 comments on commit 511f76a

Please sign in to comment.