Search code examples
grailsgrails-3.3

Default format for withFormat in Grails 3.x


In Grails this could be use for content negotiation, especially useful to implement APIs:

withFormat {
    xml { ... some code that renders XML }
    json { ... some code that renders JSON }
}

Now, if I need a default format, let's say JSON, the "... some code that renders JSON" should be executed twice, once for the JSON option and once for the "*" option that is, AFAIK the "any other matching format", which is a way to specify the default format, like:

withFormat {
    xml { ... some code that renders XML }
    json { ... some code that renders JSON }
    "*" { ... some code that renders JSON }
}

My questions are:

  1. Is that the correct way of specifying the default format as JSON?

  2. Is there a way of not repeating the same code for two options? (I mean something like: json, "*" { ... }


Solution

  • Instead of this...

    withFormat {
        xml { ... some code that renders XML }
        json { ... some code that renders JSON }
        "*" { ... some code that renders JSON }
    }
    

    Use this:

    withFormat {
        xml { ... some code that renders XML }
        "*" { ... some code that renders JSON }
    }