burnchart/proxy.coffee

59 lines
1.9 KiB
CoffeeScript
Raw Normal View History

2013-08-17 12:54:48 +00:00
#!/usr/bin/env coffee
2013-12-30 11:48:29 +00:00
_ = require 'lodash'
2013-08-17 12:54:48 +00:00
http = require 'http'
fs = require 'fs'
connect = require 'connect'
request = require 'request'
# Read the original config.
config = JSON.parse fs.readFileSync './config.json', 'utf-8'
2013-09-29 22:14:30 +00:00
# Some defaults.
config.host ?= 'api.github.com'
2013-08-17 12:54:48 +00:00
# This is the scrubbed version.
2013-09-29 21:14:24 +00:00
_.extend scrubbed = {}, config, { 'protocol': 'http', 'token': null }
2013-08-17 12:54:48 +00:00
proxy = (req, res, next) ->
end = (code, body) ->
2013-08-17 12:54:48 +00:00
res.writeHead code, {'Content-Type': 'application/json; charset=utf-8'}
res.end body
# Log it.
console.log new Date(), req.url
2013-08-17 12:54:48 +00:00
# Config?
if req.url is '/config.json'
# Refer to us like so.
# Prefer custom header x-forwarded-host if defined.
scrubbed.host = req.headers['x-forwarded-host'] or req.headers.host
return end 200, JSON.stringify scrubbed, null, 4
2013-08-17 12:54:48 +00:00
# GitHub API request?
2013-08-17 12:54:48 +00:00
if req.url.match /^\/repos/
# The default headers.
2013-12-30 11:48:29 +00:00
headers =
# See http://developer.github.com/v3/media/#beta-v3-and-the-future
'Accept': 'application/vnd.github.v3'
# See http://developer.github.com/v3/#user-agent-required
'User-Agent': 'GitHub-Burndown-Chart'
2013-08-17 12:54:48 +00:00
# Add a token?
headers.Authorization = "token #{config.token}" if config.token?
2013-09-29 22:14:30 +00:00
# Make the HTTPS request.
2013-08-17 12:54:48 +00:00
return request {
'uri': "https://#{config.host}#{req.url}"
2013-08-17 12:54:48 +00:00
headers
# Handle the response.
}, (err, _res, body) ->
return end(500) if err
end _res.statusCode, body
2013-08-17 12:54:48 +00:00
# Get handled by Connect.
2013-12-30 11:48:29 +00:00
do next
2013-08-17 12:54:48 +00:00
app = connect()
.use(proxy)
# Serve the public directory with the app, no need to launch another service.
2013-08-17 12:54:48 +00:00
.use(connect.static(__dirname + '/public'))
# Connect on an env port or go random.
2013-12-30 11:48:29 +00:00
.listen process.env.PORT, ->
console.log 'Proxy listening on port', app.address().port