Skip to content

Instantly share code, notes, and snippets.

@zedar
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zedar/e6f6cda10236fed22b68 to your computer and use it in GitHub Desktop.
Save zedar/e6f6cda10236fed22b68 to your computer and use it in GitHub Desktop.
ratpack respond by content

Ratpack handler with byContent response

Ratpack is a Java/Groovy framework for rapid development of microservices.

Define set of handlers in src/main/Ratpack.groovy. Define common prefix api for REST APIs.

import static ratpack.groovy.Groovy.groovyTemplate
import static ratpack.groovy.Groovy.ratpack
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import groovy.json.JsonBuilder
import groovy.xml.MarkupBuilder

ratpack {
  handlers {
    prefix("api") {
      handler {
        // common code for all api calls
        // log all HTTP request headers
        request.headers?.names?.each { name ->
          logger.debug("HEADER: ${name}, VALUES: ${request.headers?.getAll(name)}")
        }
        // call next handlers
      }
      
      get {
        // IMPORTANT: if HTTP header 'Accept' is not given then first declaration from inside byContent takes place.
        byContent {
          json {
            def builder = new JsonBuilder()
            builder.root {
              type: "JSON"
            }
            render builder.toString()
          }
          xml {
            def sw = new StringWriter()
            builder = new MarkupBuilder(sw)
            builder.root {
              type(a: "A", b: "B", "XML")
            }
            render sw.toString()
          }
        }
      }
    }
  }
}

Run project from inside project's folder

$ ./gradlew run

Test what is returned by different conent type:

  • JSON

      $ curl -X GET -H "Accept: application/json" http://localhost:5050/api
    
  • XML

      $ curl -X GET -H "Accept: application/xml" http://localhost:5050/api
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment