-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
90 lines (73 loc) · 2.07 KB
/
index.js
File metadata and controls
90 lines (73 loc) · 2.07 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import express from 'express';
import http from 'node:http';
import { createBareServer } from "@tomphttp/bare-server-node";
import cors from 'cors';
import path from 'node:path';
const server = http.createServer();
const app = express();
const rootDir = process.cwd();
const bareServer = createBareServer('/bare/');
const PORT = process.env.PORT || 8080;
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(rootDir, "public")));
app.get("/api/search", async (req, res) => {
const q = String(req.query.q || "").trim();
if (!q) return res.status(400).json({ error: "missing q" });
const engines = [
"https://duckduckgo.com/?q=%s",
"https://www.startpage.com/sp/search?q=%s",
"https://search.brave.com/search?q=%s",
"https://duckduckgo.com/html/?q=%s",
"https://lite.duckduckgo.com/lite/?q=%s"
];
const query = encodeURIComponent(q);
for (const tpl of engines) {
const url = tpl.replace("%s", query);
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 2000);
const r = await fetch(url, {
method: "GET",
signal: controller.signal,
headers: {
"User-Agent": "Mozilla/5.0"
}
});
clearTimeout(timer);
if (r.ok) {
return res.json({ url });
}
} catch (e) {
// fail -> next engine
}
}
return res.status(502).json({ error: "no search engine available" });
});
server.on('request', (req, res) => {
if (bareServer.shouldRoute(req)) {
bareServer.routeRequest(req, res)
} else {
app(req, res)
}
})
server.on('upgrade', (req, socket, head) => {
if (bareServer.shouldRoute(req)) {
bareServer.routeUpgrade(req, socket, head)
} else {
socket.end()
}
})
server.listen(PORT, () => {
console.log(`Server Listening on ${PORT}`);
});
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
function shutdown() {
console.log("Shutting down...");
server.close(() => {
bareServer.close();
process.exit(0);
});
}