Title here
Summary here
April 20, 20253 minutes
Hono는 빠르고 가벼운 웹 프레임워크로, 다양한 JavaScript 런타임에서 작동합니다.
이 글에서는 Hono에서 제공하는 주요 함수들의 사용법을 자세히 설명합니다.
import { Hono } from 'hono'
const app = new Hono()app.get('/', (c) => c.text('Hello Hono!'))
app.post('/submit', (c) => c.text('Submitted!'))
app.put('/update', (c) => c.text('Updated!'))
app.delete('/remove', (c) => c.text('Deleted!'))app.use('*', async (c, next) => {
console.log('Middleware executed!')
await next()
})app.get('/user/:id', (c) => {
const id = c.req.param('id') // `/user/123` → `id = "123"`
const query = c.req.query('name') // `/user/123?name=John` → `query = "John"`
return c.text(`User: ${id}, Name: ${query}`)
})app.post('/submit', async (c) => {
const body = await c.req.json() // JSON 데이터
const formData = await c.req.parseBody() // FormData
return c.json({ body, formData })
})app.get('/headers', (c) => {
const userAgent = c.req.header('User-Agent')
return c.text(`Your User-Agent: ${userAgent}`)
})
app.get('/set-cookie', (c) => {
c.cookie('session', 'abc123', { secure: true })
return c.text('Cookie set!')
})
app.get('/get-cookie', (c) => {
const session = c.req.cookie('session')
return c.text(`Session: ${session}`)
})app.get('/text', (c) => c.text('Plain Text'))
app.get('/json', (c) => c.json({ message: 'Hello JSON!' }))
app.get('/html', (c) => c.html('<h1>Hello HTML!</h1>'))app.get('/old', (c) => c.redirect('/new'))app.get('/download', (c) => {
return new Response('File content', {
headers: { 'Content-Disposition': 'attachment; filename="file.txt"' },
})
})import { streamText } from 'hono/streaming'
app.get('/stream', (c) => {
return streamText(c, async (stream) => {
for (let i = 0; i < 5; i++) {
await stream.write(`Line ${i}\n`)
await new Promise((r) => setTimeout(r, 1000))
}
})
})import { basicAuth } from 'hono/basic-auth'
app.use(
'/admin/*',
basicAuth({
username: 'admin',
password: 'secret',
})
)
app.get('/admin', (c) => c.text('You are authorized!'))import { cors } from 'hono/cors'
app.use('/api/*', cors())import { jwt } from 'hono/jwt'
app.use('/secure/*', jwt({ secret: 'my-secret-key' }))
app.get('/secure/data', (c) => {
const payload = c.get('jwtPayload')
return c.json({ data: 'Protected!', user: payload })
})import { serveStatic } from 'hono/bun' // Bun 전용
// import { serveStatic } from 'hono/cloudflare-workers' // Cloudflare Workers 전용
app.get('/static/*', serveStatic({ root: './public' }))app.notFound((c) => c.text('Not Found!', 404))app.onError((err, c) => {
console.error(err)
return c.text('Internal Server Error', 500)
})app.get('/error', (c) => {
throw new Error('Something went wrong!')
})type Bindings = {
DB: D1Database
SECRET: string
}
const app = new Hono<{ Bindings: Bindings }>()
app.get('/env', (c) => {
const db = c.env.DB
const secret = c.env.SECRET
return c.json({ db, secret })
})export default appBun.serve({
fetch: app.fetch,
port: 3000,
})import { serve } from '@hono/node-server'
serve(app, (info) => {
console.log(`Listening on http://localhost:${info.port}`)
})Hono는 빠르고 가벼운 웹 프레임워크로, 다양한 기능을 제공합니다.
이 가이드를 통해 주요 함수들을 익히고, 효율적으로 사용해 보세요!
더 자세한 내용은 공식 문서 (hono.dev)를 참고하세요.