crazy4groovy
12/17/2015 - 8:46 PM

spark.groovy

@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() })