Last active
December 25, 2024 12:43
-
-
Save laiso/c6b070eba8a62e3995e6936689b263d0 to your computer and use it in GitHub Desktop.
esbuild hono-llrt.js --outfile=bundle.mjs --platform=node --target=es2020 --format=esm --bundle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createServer } from 'net' | |
import { Hono } from 'hono' | |
// import { Hono } from './dist' | |
const PORT = 3000 | |
/** | |
* TODO: Remove globalThis.Response | |
* The Response object is normally supported by the runtime. | |
* This is a workaround for the issue where `new Response` is not | |
* accessible in the global scope as of LLRT 0.1.6-beta. | |
*/ | |
globalThis.Response = class { | |
constructor(body, status = 200, statusText = 'OK', headers = {}) { | |
this.body = body | |
this.status = status | |
this.statusText = statusText | |
this.headers = headers | |
} | |
async text() { | |
return this.body | |
} | |
} | |
const app = new Hono() | |
app.get('/', (c) => c.text('Hello Hono on LLRT!')) | |
const server = createServer((socket) => { | |
socket.on('error', (error) => { | |
console.error('Socket error:', error) | |
socket.end() | |
}) | |
socket.on('data', async (data) => { | |
try { | |
const requestString = data.toString() | |
const requestLines = requestString.split('\r\n') | |
const requestLine = requestLines[0].split(' ') | |
const headers = {} | |
for (let i = 1; i < requestLines.length; i++) { | |
const line = requestLines[i] | |
if (line) { | |
const [key, ...valueParts] = line.split(': ') | |
headers[key] = valueParts.join(': ') | |
} | |
} | |
const method = requestLine[0] | |
const path = requestLine[1] | |
const protocol = requestLine[2] | |
const url = `http://localhost:${PORT}${path}` | |
const request = new Request(url, { | |
method, | |
path, | |
protocol, | |
headers, | |
}) | |
console.log('Received request:', request) | |
const response = await app.fetch(request) | |
console.log('Converted response:', response) | |
const body = await response.text() | |
let responseHeaders = '' | |
for (const [key, value] of Object.entries(response.headers)) { | |
responseHeaders += `${key}: ${value}\r\n` | |
} | |
const httpResponse = `HTTP/1.1 ${response.status} ${response.statusText}\r\n${responseHeaders}\r\n${body}` | |
socket.write(httpResponse) | |
socket.end() | |
} catch (error) { | |
console.error('Error handling request:', error) | |
socket.write('HTTP/1.1 500 Internal Server Error\r\n\r\n') | |
socket.end() | |
} | |
}) | |
}) | |
server.listen(PORT, () => { | |
console.log(`Server listening on http://localhost:${PORT}/`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment