forked from tina-hello/doh-cf-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (49 loc) · 1.71 KB
/
index.js
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
// SPDX-License-Identifier: 0BSD
const doh = 'https://security.cloudflare-dns.com/dns-query'
const dohjson = 'https://security.cloudflare-dns.com/dns-query'
const contype = 'application/dns-message'
const jstontype = 'application/dns-json'
const r404 = new Response(null, {status: 404});
// developers.cloudflare.com/workers/runtime-apis/fetch-event/#syntax-module-worker
export default {
async fetch(r, env, ctx) {
return handleRequest(r);
},
};
async function handleRequest(request) {
// when res is a Promise<Response>, it reduces billed wall-time
// blog.cloudflare.com/workers-optimization-reduces-your-bill
let res = r404;
const { method, headers, url } = request
const searchParams = new URL(url).searchParams
if (method == 'GET' && searchParams.has('dns')) {
var pa = searchParams.get('dns');
console.log("收到解析请求:"+ pa )
res = fetch(doh + '?dns=' + pa, {
method: 'GET',
headers: {
'Accept': contype,
}
});
} else if (method === 'POST' && headers.get('content-type') === contype) {
// streaming out the request body is optimal than awaiting on it
const rostream = request.body;
res = fetch(doh, {
method: 'POST',
headers: {
'Accept': contype,
'Content-Type': contype,
},
body: rostream,
});
} else if (method === 'GET' && headers.get('Accept') === jstontype) {
const search = new URL(url).search
res = fetch(dohjson + search, {
method: 'GET',
headers: {
'Accept': jstontype,
}
});
}
return res;
}