Skip to content

Instantly share code, notes, and snippets.

@laiso
Last active April 14, 2024 21:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laiso/c6b070eba8a62e3995e6936689b263d0 to your computer and use it in GitHub Desktop.
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
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