Skip to content

Instantly share code, notes, and snippets.

@dnoseda
Forked from ataylor284/webapp.groovy
Last active August 29, 2015 14:22
Show Gist options
  • Save dnoseda/f96f42b52559e8baeb88 to your computer and use it in GitHub Desktop.
Save dnoseda/f96f42b52559e8baeb88 to your computer and use it in GitHub Desktop.
import com.sun.net.httpserver.*
Object.metaClass.webapp = {
{ path ->
try {
def attrs = path.split('/')[1..-1]
[200, owner.delegate.invokeMethod(attrs.head(), attrs.tail() as Object[]) as String]
} catch (Exception e) {
[500, e as String]
}
}
}
def runWebApp(app, port = 9292) {
HttpServer server = HttpServer.create(new InetSocketAddress(port),0)
server.createContext('/', { HttpExchange exchange ->
def (code, body) = app.call(exchange.requestURI.path)
exchange.sendResponseHeaders(code,0);
exchange.responseBody.write(body.bytes)
exchange.responseBody.close();
} as HttpHandler)
server.start();
}
runWebApp([].webapp())
// ^^^^^^^^^^^
// | (x)
// ROFLSCALE DB ---/
//
// http://localhost:9292/push/1 -> true
// http://localhost:9292/push/2 -> true
// http://localhost:9292/push/3 -> true
// http://localhost:9292/toString -> [1, 2, 3]
// http://localhost:9292/pop -> 3
// http://localhost:9292/shift ... no shift in groovy :(
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment