Skip to content

Instantly share code, notes, and snippets.

@smaldini
Last active August 29, 2015 14:14
Show Gist options
  • Save smaldini/b95b8d325dafa4de608f to your computer and use it in GitHub Desktop.
Save smaldini/b95b8d325dafa4de608f to your computer and use it in GitHub Desktop.
Preliminary HTTP support in reactor-net
def "http responds to requests from clients"() {
given: "a simple HttpServer"
//Listen on localhost using default impl (Netty) and assign a global codec to receive/reply String data
def server = NetStreams.httpServer {
it.codec(StandardCodecs.STRING_CODEC).listen(port)
}
//Prepare a client using default impl (Netty) to connect on http://localhost:port/ and assign global codec to send/receive String data
def client = NetStreams.httpClient {
it.codec(StandardCodecs.STRING_CODEC).connect("localhost", port)
}
when: "the server is prepared"
//prepare post request consumer on /test/* and capture the URL parameter "param"
server.post('/test/{param}') { req ->
//log then transform then log received http request content from the request body and the resolved URL parameter "param"
//the returned stream is bound to the request stream and will auto read/close accordingly
req
.log('server-received')
.map { it + ' ' + req.param('param') + '!' }
.log('server-reply')
}
then: "the server was started"
server?.start()?.awaitSuccess(5, TimeUnit.SECONDS)
when: "data is sent with Reactor HTTP support"
//prepare an http post request-reply flow
def content = client.post('/test/World') { req ->
//prepare content-type
req.header('Content-Type', 'text/plain')
//return a producing stream to send some data along the request
Streams
.just("Hello")
.log('client-send')
}.flatMap { replies ->
//successful request, listen for replies
replies
.log('client-received')
.next()
}.onError{
//something failed during the request or the reply processing
println "Failed requesting server: $it"
}
then: "data was received"
//execute the request now
client.open().awaitSuccess()
//the produced reply should be there soon
content.await() == "Hello World!"
cleanup: "the client/server where stopped"
//note how we order first the client then the server shutdown
client?.close()?.flatMap { server.shutdown() }?.awaitSuccess(5, TimeUnit.SECONDS)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment