Skip to content

Instantly share code, notes, and snippets.

@rhart
Created December 20, 2014 23:09
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rhart/eb1b701f348a155f2dad to your computer and use it in GitHub Desktop.
Ratpack HTTP Proxy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import ratpack.handling.Context
import ratpack.handling.Handler
import ratpack.http.client.HttpClient
import ratpack.http.client.StreamedResponse
import ratpack.http.MutableHeaders
import ratpack.http.client.RequestSpec
import static ratpack.groovy.Groovy.ratpack
final Logger log = LoggerFactory.getLogger(Ratpack.class);
class BlockedHostHandler implements Handler {
def blockedHosts = ['www.asos.co.uk']
@Override
void handle(Context context) throws Exception {
if (blockedHosts.contains(context.request.headers.host)) {
context.redirect(302, "http://ratpack-foaas.herokuapp.com/you/no $context.request.headers.host allowed/the Boss")
}
context.next()
}
}
ratpack {
handlers {
handler new BlockedHostHandler()
handler { HttpClient httpClient ->
log.info("Proxy to: $request.rawUri")
httpClient.streamRequest(new URI(request.rawUri)) { RequestSpec spec ->
spec.headers.copy(request.headers)
} then { StreamedResponse responseStream ->
responseStream.send(response) { MutableHeaders headers ->
def via = '1.1 Ratpack Proxy'
via = headers.get('Via') ? via + ', ' + headers.get('Via') : via
headers.set('Via', via)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment