Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Forked from mattn/spark.groovy
Last active December 18, 2015 17:07
Show Gist options
  • Save crazy4groovy/406c26b13e61540c821c to your computer and use it in GitHub Desktop.
Save crazy4groovy/406c26b13e61540c821c to your computer and use it in GitHub Desktop.
@Grab('com.sparkjava:spark-core:2.1')
import static spark.Spark.*
import groovy.json.JsonBuilder
Object.metaClass.asJson = {
def builder = new JsonBuilder(delegate);
builder.toString()
}
get('/hi', { req, res -> ('hi ' + req.queryParams('name') ?: ' World!') })
get('/hi2', { req, res -> ('hi ' + req.queryMap().toMap()['name']?.get(0) ?: ' World!') })
get('/headers', { req, res -> req.headers() })
get('/url', { req, res -> req.url() })
get('/methods', { req, res -> req.metaClass.methods*.name.sort().unique() })
get('/everything', { req, res ->
List methods = req.metaClass.methods*.name.sort().unique();
String coll = '';
methods.each { method ->
try { coll += "$method: ${req."$method"()}\n<br>" }
catch (Exception ignore) { coll += " !Error: $method -- '$ignore'\n<br>" }
}
return coll
})
Map map = [:]
map['foo'] = 'ハローワールド'
map['bar'] = [1, 2, 3]
map['boo'] = ['hoge' : 'aaa', 'fuga' : [1, 2, ['obj':true]]]
get('/map', { req, res -> map.asJson() })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment