Skip to content

Instantly share code, notes, and snippets.

@jhs
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhs/d5763dfe305fd8b18710 to your computer and use it in GitHub Desktop.
Save jhs/d5763dfe305fd8b18710 to your computer and use it in GitHub Desktop.
Legacy http server with Hapi
// This file demonstrates my desire to hook a "legacy" http server into
// a Hapi route.
var http = require('http')
var legacy_server = http.createServer(legacy_handler)
legacy_server.listen(8081)
function legacy_handler(request, response) {
response.end('I am a standard handler\n')
}
// Okay, great. Now suppose I want to hook this legacy application into a
// newer Hapi application, for example under a vhost or a /deprecated namespace.
var Hapi = require('hapi')
var server = new Hapi.Server(8080, "0.0.0.0")
server.route({path:'/', method:'*', handler:hapi_handler})
function hapi_handler(request, reply) {
reply('I am a Hapi handler\n')
}
if (false)
// I want this. hapi_wrap() wraps the legacy server into a Hapi handler
// (hypothetically).
server.route({path:'/legacy', method:'*', handler:hapi_wrap(legacy_server)})
else
// But all I can do is this, function by function, handler by handler.
server.route({path:'/legacy', method:'*', handler:kludge_handler})
server.start()
// This is sort-of what I want except I wish I did not need to know
// legacy server implementation and handler functions.
function kludge_handler(request, reply) {
var req = request.raw.req
var res = request.raw.res
legacy_handler(req, res)
}
$ # Hit the legacy server
$ curl localhost:8081
I am a standard handler
$ # Hit the Hapi server
$ curl localhost:8080
I am a Hapi handler
$ # Hit the legacy application via the Hapi server
$ curl localhost:8080/legacy
I am a standard handler
@hueniverse
Copy link

Wrapping existing http dispatch function for use as a hapi handler is generally a bad idea. But if you must, add to your kludge_handler at the end: reply.close(false); so that hapi can finish handling the request without messing with you legacy logic (https://github.com/spumko/hapi/blob/master/docs/Reference.md#replycloseoptions).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment