boilerplate-lambda-container/notes/hello-hono/main.ts

84 lines
1.7 KiB
TypeScript

import { Hono } from 'hono'
const app = new Hono()
// return text
app.get('/', (c) => {
return c.text('Hello Hono!')
})
// return JSON
app.get('/json', (c) => {
return c.json({
ok: true,
message: 'Hello Hono!',
})
})
// query params: curl 'localhost:8000/posts/9?page=7'
app.get('/posts/:id', (c) => {
const page = c.req.query('page')
const id = c.req.param('id')
c.header('X-Message', 'Hi!')
return c.text(`You want to see ${page} of ${id}`)
})
// create: curl -X POST localhost:8000/posts
app.post('/posts', (c) => c.text('Created!', 201))
// delete: curl -X DELETE localhost:8000/posts/8
app.delete('/posts/:id', (c) =>
c.text(`${c.req.param('id')} should be deleted!`)
)
// return raw response
app.get('/raw', () => {
return new Response('Hello Hono!')
})
/*
// return HTML using JSX (Deno's linter hates it)
const View = () => {
return (
<html>
<body>
<h1>Hello Hono!</h1>
</body>
</html>
)
}
app.get('/page', (c) => {
return c.html(<View />)
})
*/
// "Middleware can do the hard work for you. For example, add in Basic Authentication."
// curl -u admin:secret http://localhost:8000/admin
import { basicAuth } from 'hono/basic-auth'
app.use(
'/admin/*',
basicAuth({
username: 'admin',
password: 'secret',
})
)
app.get('/admin', (c) => {
return c.text('You are authorized!')
})
// "There are Adapters for platform-dependent functions, e.g., handling static files or WebSocket.
// For example, to handle WebSocket in Cloudflare Workers, import hono/cloudflare-workers."
/*
import { upgradeWebSocket } from 'hono/cloudflare-workers'
app.get(
'/ws',
upgradeWebSocket((c) => {
// ...
})
)
*/
Deno.serve(app.fetch)