Skip to content

CBOR

CBORRFC 8949에 정의된 객체를 직렬화하는 바이너리 포맷이다. JSON과 호환되며, 효율적인 데이터 교환이 필요한 네트워크 통신이나 IoT 디바이스와 같은 리소스가 제한된 환경에서 사용하기 적합하다.

다음은 cbor2 패키지를 사용해 CBOR로 응답하는 예제이다.

ts
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
import { encode } from 'cbor2'

const app = new Hono()

declare module 'hono' {
  interface ContextRenderer {
    (content: any): Response | Promise<Response>
  }
}

const cborRenderer = createMiddleware(async (c, next) => {
  c.header('Content-Type', 'application/cbor')
  c.setRenderer((content) => {
    return c.body(encode(content))
  })
  await next()
})

app.use(cborRenderer)

app.get('/', (c) => {
  return c.render({ message: 'hello CBOR!' })
})

export default app

다음 커맨드를 사용해 응답을 확인할 수 있다.

plaintext
$ curl -s http://localhost:3000/ | hexdump -C
00000000  a1 67 6d 65 73 73 61 67  65 6b 68 65 6c 6c 6f 20  |.gmessagekhello |
00000010  43 42 4f 52 21                                    |CBOR!|
00000015

또한 CBOR 플레이그라운드에서 JSON 객체로 디코딩되는지 확인할 수 있다.

plaintext
A1                           # map(1)
   67                        # text(7)
      6D657373616765         # "message"
   6B                        # text(11)
      68656C6C6F2043424F5221 # "hello CBOR!"
json
{ "message": "hello CBOR!" }

관련 자료

Released under the MIT License.