Skip to content

Instantly share code, notes, and snippets.

@ldaley
Created July 16, 2014 08:36
Show Gist options
  • Save ldaley/f5b01de44b0bae8d5fd7 to your computer and use it in GitHub Desktop.
Save ldaley/f5b01de44b0bae8d5fd7 to your computer and use it in GitHub Desktop.
Bootstrapping an embedded ratpack app
import ratpack.groovy.handling.GroovyChainAction
import ratpack.guice.BindingsSpecAction
import ratpack.guice.Guice
import ratpack.handling.Context
import ratpack.launch.LaunchConfigBuilder
import ratpack.server.BindAddress
import ratpack.server.PublicAddress
import ratpack.server.RatpackServerBuilder
class HostHeaderBasedPublicAddress implements PublicAddress {
@Override
URI getAddress(Context context) {
def bindAddress = context.bindAddress
def host = context.request.headers.get("host")
if (host) {
new URI("http://$host:$bindAddress.port")
} else {
new URI("http://$bindAddress.host:$bindAddress.port")
}
}
}
def launchConfig = LaunchConfigBuilder.
noBaseDir().
build { launchConfig ->
try {
def handlers = new GroovyChainAction() {
protected void execute() throws Exception {
get { PublicAddress publicAddress ->
render "public address: ${publicAddress.getAddress(context)}"
}
}
}
def bindings = new BindingsSpecAction() {
protected void execute() throws Exception {
bind(PublicAddress, HostHeaderBasedPublicAddress)
}
}
Guice.handler(launchConfig, bindings, handlers)
} catch (e) {
e.printStackTrace()
}
}
def server = RatpackServerBuilder.build(launchConfig)
server.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment