{"id":19168137,"url":"https://github.com/masx200/http-https-http2-polyglot","last_synced_at":"2026-06-18T14:30:16.934Z","repository":{"id":37089120,"uuid":"257627953","full_name":"masx200/http-https-http2-polyglot","owner":"masx200","description":"Serve http and https and http2 connections over the same port with node.js，and add typescript support","archived":false,"fork":false,"pushed_at":"2023-03-01T13:57:31.000Z","size":318,"stargazers_count":2,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-04T01:11:10.492Z","etag":null,"topics":["http","http2","server","tls"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/masx200.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-04-21T14:49:21.000Z","updated_at":"2023-09-21T00:22:17.000Z","dependencies_parsed_at":"2024-11-09T09:51:31.143Z","dependency_job_id":null,"html_url":"https://github.com/masx200/http-https-http2-polyglot","commit_stats":{"total_commits":318,"total_committers":7,"mean_commits":45.42857142857143,"dds":"0.32389937106918243","last_synced_commit":"ae76a719432499541c0bf8f859314b7cfdc761d9"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/masx200%2Fhttp-https-http2-polyglot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/masx200%2Fhttp-https-http2-polyglot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/masx200%2Fhttp-https-http2-polyglot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/masx200%2Fhttp-https-http2-polyglot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/masx200","download_url":"https://codeload.github.com/masx200/http-https-http2-polyglot/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240248426,"owners_count":19771473,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["http","http2","server","tls"],"created_at":"2024-11-09T09:41:23.845Z","updated_at":"2026-06-18T14:30:16.865Z","avatar_url":"https://github.com/masx200.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Description\n\n说明\n\nServe http and https and http2 connections over the same port with node.js，\n\nand add \"typescript\" support。\n\nThanks to the original author，\n\n使用 node.js 在同一端口上服务 http 和 https 以及 http2 连接，\n\n优化和重构，\n\n并添加\"TYPESCRIPT\"支持。\n\n多亏了原作者，\n\nhttps://github.com/mscdex/httpolyglot\n\nhttps://github.com/httptoolkit/httpolyglot\n\n# Requirements\n\n要求\n\n[node.js](http://nodejs.org/) -- v12.0.0 or newer\n\n# Install\n\n安装\n\n```shell\nyarn add @masx200/http-https-http2-polyglot\n```\n\n# Connection protocol judgment\n\n连接协议判断\n\n确定连接是否通过 tls。\n\nDetermine if the connection is over tls.\n\n```js\nconst istls = true === req.socket[\"encrypted\"];\n```\n\nDetermine if the connection is `http/2`.\n\n确定连接是否为“ http / 2”。\n\n```js\nconst ishttp2 = \"h2\" === req.socket.alpnProtocol;\n```\n\n# Examples\n\n例子\n\n`http2` 服务器推送\n\n`http2` server push\n\nhttps://github.com/masx200/http-https-http2-polyglot/blob/master/test/push.js\n\n```js\nimport { createServer } from \"../dist/index.js\";\nimport { cert, key } from \"./key-cert.js\";\nconst port = 9002;\nconst server = createServer({ key, cert }, async (req, res) =\u003e {\n    if (req.url == \"/main.js\") {\n        res.statusCode = 200;\n        res.setHeader(\"content-type\", \"application/javascript\");\n        res.end('alert(\"not from push stream\")');\n        return;\n    } else {\n        res.writeHead(200, { \"Content-Type\": \"text/html\" });\n        if (\"function\" === typeof res[\"createPushResponse\"]) {\n            res.createPushResponse(\n                { \":method\": \"GET\", \":path\": \"/main.js\" },\n                (err, stream) =\u003e {\n                    if (err) {\n                        console.error(err);\n                    } else {\n                        stream.setHeader(\n                            \"content-type\",\n                            \"application/javascript\"\n                        );\n                        stream.end('alert(\"hello from push stream!\");');\n                    }\n                }\n            );\n        }\n        res.end('push\u003cscript src=\"/main.js\"\u003e\u003c/script\u003e');\n    }\n});\nserver.listen(port, \"localhost\", function () {\n    console.log(\"httpolyglot server listening on port \" + port);\n});\n```\n\nWebsocket server\n\nWebsocket 服务器\n\nhttps://github.com/masx200/http-https-http2-polyglot/blob/master/test/websocket.js\n\n```js\nimport fs from \"fs\";\nimport path, { dirname } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport ws from \"ws\";\nimport { createServer } from \"../dist/index.js\";\nimport { cert, key } from \"./key-cert.js\";\nconst port = 8999;\nconst wsServer = new ws.Server({ noServer: true });\nwsServer.on(\"connection\", (websocket, req) =\u003e {\n    websocket.on(\"error\", () =\u003e {});\n    websocket.send(JSON.stringify(req.headers));\n    websocket.send(\n        (true === req.socket[\"encrypted\"] ? \"HTTPS\" : \"HTTP\") + \" Connection!\"\n    );\n});\n// @ts-ignore\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst server = createServer(\n    {\n        key,\n        cert,\n    },\n    async function (req, res) {\n        if (req.url === \"/\") {\n            res.writeHead(200, { \"Content-Type\": \"text/html\" });\n\n            res.end(\n                \"websocket\u003cscript type='module' src='./index.js'\u003e\u003c/script\u003e\"\n            );\n        } else if (req.url === \"/index.js\") {\n            res.writeHead(200, { \"Content-Type\": \"text/javascript\" });\n            const jsfile = await fs.promises.readFile(\n                path.join(__dirname, \"index.js\")\n            );\n            res.write(jsfile);\n            res.end();\n        } else {\n            res.statusCode = 404;\n            res.write(\"404\");\n            res.end();\n        }\n    },\n    function (req, socket, head) {\n        wsServer.handleUpgrade(req, socket, head, function done(ws) {\n            wsServer.emit(\"connection\", ws, req);\n        });\n    }\n);\n//server.on(\"request\", console.log);\n//server.on(\"upgrade\", console.log);\nserver.listen(port, \"localhost\", function () {\n    console.log(\"httpolyglot server listening on port \" + port);\n});\n```\n\nSimple Determine the connection protocol\n\n简单确定连接协议\n\n```javascript\nimport * as httpolyglot from \"@masx200/http-https-http2-polyglot\";\nimport fs from \"fs\";\n\nconst port = 9000;\nconst server = httpolyglot.createServer(\n    {\n        key: fs.readFileSync(\"server.key.pem\"),\n        cert: fs.readFileSync(\"server.crt.pem\"),\n    },\n    function (req, res) {\n        res.writeHead(200, { \"Content-Type\": \"text/html\" });\n        res.end(\n            (true === req.socket[\"encrypted\"] ? \"HTTPS\" : \"HTTP\") +\n                \" Connection!\"\n        );\n    }\n);\nserver.listen(port, \"localhost\", function () {\n    console.log(\"httpolyglot server listening on port \" + port);\n});\n```\n\nredirect all http connections to https:\n\n将所有 http 连接重定向到 https\n\nhttps://github.com/masx200/http-https-http2-polyglot/blob/master/test/redirect.js\n\n```js\nimport { createServer } from \"../dist/index.js\";\nimport { cert, key } from \"./key-cert.js\";\n// @ts-ignore\n\nconst port = 9001;\nconst server = createServer(\n    {\n        key,\n        cert,\n    },\n    function (req, res) {\n        if (true === req.socket[\"encrypted\"]) {\n            res.writeHead(200, { \"Content-Type\": \"text/html\" });\n            res.end(\"Welcome, HTTPS user!\");\n        } else {\n            const host = req.headers[\"host\"] || req.authority;\n            const originurl = req.url || \"\";\n            const tourl = new URL(originurl, \"https://\" + host);\n            tourl.port = String(port);\n            res.writeHead(302, {\n                Location: tourl.href,\n                \"Content-Type\": \"text/html\",\n            });\n            res.write(\"302\");\n            return res.end();\n        }\n    }\n);\n\nserver.listen(port, \"localhost\", function () {\n    console.log(\"httpolyglot server listening on port \" + port);\n});\n```\n\ncreate a \"404 not found\" server\n\n创建“ 404 未找到”服务器\n\nhttps://github.com/masx200/http-https-http2-polyglot/blob/master/test/notfound.js\n\n```js\nimport { createServer } from \"../dist/index.js\";\nimport { cert, key } from \"./key-cert.js\";\nconst port = 8998;\n// @ts-ignore\n\nconst server = createServer({\n    key,\n    cert,\n});\n\nserver.listen(port, \"localhost\", function () {\n    console.log(\"httpolyglot server listening on port \" + port);\n});\n```\n\n# API\n\n## Exports\n\nhttps://github.com/masx200/http-https-http2-polyglot/blob/master/dist/index.d.ts\n\n**createServer** - Creates and returns a new Server instance.\n\n创建并返回一个新的 Server 实例。\n\n```ts\ndeclare function createServer(\n    options: ServerOptions,\n    requestListener?: RequestListener,\n    upgradeListener?: UpgradeListener\n): http2.Http2SecureServer \u0026 http.Server;\n```\n\nThe `requestListener` is a function which is automatically added to the\n'request' event\n\nThe `upgradeListener` is a function which is automatically added to the\n'upgrade' event\n\nIf no \"requestListener\" or \"upgradeListener\" is provided, the default \"404 not\nfound\" listener will be used instead.\n\nEvent \"clientError\", If a client connection emits an 'error' event, it will be\nforwarded here.\n\nEvent \"tlsClientError\", The 'tlsClientError' event is emitted when an error\noccurs before a secure connection is established.\n\nEvent: 'listening',Emitted when the server has been bound after calling\n`server.listen()`.\n\nEvent: 'close', Emitted when the server closes\n\nEvent: 'error',Emitted when an error occurs on the server\n\nOnly \"requestListener\" will be called when the \"request\" event occurs.\n\nOnly \"upgradeListener\" will be called when the \"upgrade\" event occurs.\n\nDo not add \"request\" or \"upgrade\" event listener because it is not recommended\nto add multiple event listeners for \"request\"or \"upgrade\".\n\n`requestListener`是一个自动添加到'request'事件的函数\n\n“ upgradeListener”是一个自动添加到“ upgrade”事件中的函数\n\n如果未提供“ requestListener”或“ upgradeListener”，则将使用默认的“ 404 not found”监听器。\n\n事件“ clientError”，如果客户端连接发出`error`事件，它将在此处转发。\n\n事件“ tlsClientError”，在建立安全连接之前发生错误时，将发出“ tlsClientError”事件。\n\n事件：'listening'，在调用`server.listen（）`后绑定服务器时触发。\n\n事件：“ close”，在服务器关闭时发出\n\n事件：`error`，在服务器上发生错误时发出\n\n发生“ request”事件时，仅将调用“ requestListener”。\n\n发生`upgrade`事件时，仅会调用“ upgradeListener”。\n\n不要添加`request`或`request`事件侦听器，因为不建议为`request`或`request`添加多个事件侦听器。\n\n# How it Works\n\n这个怎么运作\n\nhttps://github.com/lvgithub/blog/blob/master/http_and_https_over_same_port/README.MD\n\nTLS and HTTP connections are easy to distinguish based on the first byte sent by\nclients trying to connect. See this comment for more information.\n\nTLS 和 HTTP 连接很容易根据尝试连接的客户端发送的第一个字节进行区分。有关更多信息，请参见此评论。\n\nhttps://github.com/mscdex/httpolyglot/issues/3#issuecomment-173680155\n\nhttps://github.com/httptoolkit/httpolyglot/blob/master/lib/index.js\n\n# test\n\n测试\n\n```powershell\nyarn install\n```\n\n```powershell\nyarn build\n```\n\n```powershell\nyarn generate\n```\n\n```powershell\nyarn serve\n```\n\n```powershell\nyarn test\n```\n\n```powershell\nyarn curl\n```\n\n```powershell\nyarn open\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmasx200%2Fhttp-https-http2-polyglot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmasx200%2Fhttp-https-http2-polyglot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmasx200%2Fhttp-https-http2-polyglot/lists"}