At this moment my REST API works on PHP, and is running behind Apache2/Nginx (on Apache2 actually, migration to Nginx is in progress), but after reading about Golang and Node.js performance for rest, i am thinking about migrating my REST from PHP to one of this variants, but where i stuck is how to migrate only some of routes, not whole REST at one.
For example now i have two routes
/users
and /articles
apache is listening for 80 port, and then with PHP help return response for them, but what if i want to migrate /articles
to Node.js? How my webserver will know what for /articles
he need to call Node.js if Node.js will be on different port, but for /users
still use PHP?
Found pretty good solution from my colleagues, just handle request with nginx and redirect to another server if request uri contains something, like this:
server {
listen 127.0.0.1:80;
server_name localhost.dev;
location ~* ^/[a-zA-Z0-9]+_[a-zA-Z0-9]+_(?<image_id>[0-9]+).* {
include proxy_headers.conf;
proxy_set_header X-Secure False;
add_header X-Image-Id $image_id;
access_log off;
proxy_pass http://localhost-image-cache;
proxy_next_upstream off;
}
}
upstream localhost-image-cache {
hash $server_name$image_id consistent;
server 127.0.0.1:81 max_fails=0;
keepalive 16;
}
You can set up the new Node.js REST API to use your old PHP REST API and replace the endpoints in the Node.js REST API when ready.
Here's an example using Hapi.js (but you could use any Node.js RESTful framework):
const Hapi = require('hapi');
const request = require('request');
const server = new Hapi.Server();
server.connection({ port: 81, host: 'localhost' });
server.route({
method: 'GET',
path: '/new',
handler: (req, reply) => {
reply('Hello from Node.js API');
}
});
server.route({
method: 'GET',
path: '/{endpoint}',
handler: (req, reply) => {
request.get(`http://localhost:80/${req.params.endpoint}`)
.on('response', (response) => {
reply(response);
});
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
You could run both PHP and Node.js on the same server (using different ports), but you're probably better to run them on separate servers in the same network. Once you've moved all the endpoints, you'll not want PHP/etc on your server.