Node.jsのhttp.IncommingMessage
をHTTP形式の文字列に変換するデバッグ用関数を作ったので紹介します。
どんな関数かというと、次のように第一引数にhttp.IncommingMessage
オブジェクトを渡すと:
textifyRequest(req)
下記のような文字列をPromise
で返す関数です:
POST /foobar HTTP/1.1
Host: localhost:9000
Connection: close
Transfer-Encoding: chunked
hello
http.IncommingMessage
をHTTP形式の文字列に変換する関数
const textifyRequest = (req: IncomingMessage): Promise<string> =>
new Promise(resolve => {
let text = `${req.method} ${req.url} HTTP/${req.httpVersion}\n`
// serialize headers
let nextKey = undefined as string | undefined
for (let keyOrValue of req.rawHeaders) {
if (nextKey === undefined) {
nextKey = keyOrValue
} else {
text += `${nextKey}: ${keyOrValue}\n`
nextKey = undefined
}
}
text += '\n'
// serialize body
req
.on('data', chunk => text += chunk)
.on('readable', () => req.read())
.on('end', () => resolve(text))
})
使用例
// HTTPサーバ
http.createServer((req: IncomingMessage, res: ServerResponse): void => {
textifyRequest(req).then(console.log) // リクエストを受け取ったところに仕込む
res.end()
}).listen(9000, () => {
// 上で立てたHTTPサーバにリクエストを送ってみる
const req = http.request({ host: 'localhost', port: 9000, method: 'POST', path: '/foobar' })
req.write('hello')
req.end()
})
実行結果
POST /foobar HTTP/1.1
Host: localhost:9000
Connection: close
Transfer-Encoding: chunked
hello
注意点
HTTPボディを文字列バッファに積んで返すので、データサイズの大きいリクエストには不向きな実装になっています。