Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic proxy support #39

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ serve({
headers: {
'Access-Control-Allow-Origin': '*',
foo: 'bar'
},

// Set up simple proxy
// this will route all traffic starting with
// `/api` to http://localhost:8181/api
proxy: {
api: 'http://localhost:8181'
}
})
```
Expand Down
103 changes: 75 additions & 28 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readFile } from 'fs'
import { createServer as createHttpsServer } from 'https'
import { createServer } from 'http'
import https, { createServer as createHttpsServer } from 'https'
import http, { createServer } from 'http'
import { resolve } from 'path'

import mime from 'mime'
Expand All @@ -22,41 +22,83 @@ function serve (options = { contentBase: '' }) {
options.headers = options.headers || {}
options.https = options.https || false
options.openPage = options.openPage || ''
options.proxy = options.proxy || {}
mime.default_type = 'text/plain'

const requestListener = (request, response) => {
// Use http or https as needed
const http_s = options.https ? https : http

const proxies = Object.keys(options.proxy).map(proxy => ({
proxy,
destination: options.proxy[proxy],
test: new RegExp(`\/${proxy}`)
}))


const requestListener = (request, response) => {
// Remove querystring
const urlPath = decodeURI(request.url.split('?')[0])

Object.keys(options.headers).forEach((key) => {
response.setHeader(key, options.headers[key])
})

readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {
if (!error) {
return found(response, filePath, content)
}
if (error.code !== 'ENOENT') {
response.writeHead(500)
response.end('500 Internal Server Error' +
'\n\n' + filePath +
'\n\n' + Object.values(error).join('\n') +
'\n\n(rollup-plugin-serve)', 'utf-8')
return
}
if (options.historyApiFallback) {
var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'
readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {
if (error) {
notFound(response, filePath)
} else {
found(response, filePath, content)
}
})
} else {
notFound(response, filePath)
}
})
// Find the appropriate proxy for the request if one exists
const proxy = proxies.find(({ test }) => request.url.match(test))

// If a proxy exists, forward the request to the appropriate server
if (proxy && proxy.destination) {
const { destination } = proxy
const newDestination = `${destination}${request.url}`
const { headers, method, statusCode } = request

// Get the request contents
let body = '';
request.on('data', chunk => body += chunk)

// Forward the request
request.on('end', () => {
const proxyRequest = http_s
.request(newDestination, { headers, method }, (proxyResponse) => {
let data = ''
proxyResponse.on('data', chunk => data += chunk)
proxyResponse.on('end', () => {
Object.keys(proxyResponse.headers).forEach(key => response.setHeader(key, proxyResponse.headers[key]))
foundProxy(response, proxyResponse.statusCode, data)
})
})
.end(body, 'utf-8')

proxyRequest.on('error', err => console.error(`There was a problem with the request for ${request.url}: ${err}`))
proxyRequest.end()
})
} else {
readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {
if (!error) {
return found(response, filePath, content)
}
if (error.code !== 'ENOENT') {
response.writeHead(500)
response.end('500 Internal Server Error' +
'\n\n' + filePath +
'\n\n' + Object.values(error).join('\n') +
'\n\n(rollup-plugin-serve)', 'utf-8')
return
}
if (options.historyApiFallback) {
var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'
readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {
if (error) {
notFound(response, filePath)
} else {
found(response, filePath, content)
}
})
} else {
notFound(response, filePath)
}
})
}
}

// release previous server instance if rollup is reloading configuration in watch mode
Expand Down Expand Up @@ -127,6 +169,11 @@ function found (response, filePath, content) {
response.end(content, 'utf-8')
}

function foundProxy (response, status, content) {
response.writeHead(status)
response.end(content, 'utf-8')
}

function green (text) {
return '\u001b[1m\u001b[32m' + text + '\u001b[39m\u001b[22m'
}
Expand Down