Default format for withFormat in Grails 3.x

81 Views Asked by At

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, "*" { ... }

2

There are 2 best solutions below

1
Jeff Scott Brown On BEST ANSWER

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 }
}
7
Orubel On

The one problem with this is that it is highly redundant and would have to be done in EVERY CONTROLLER METHOD. Would suggest moving this functionality to HandlerInterceptor or using something like Beapi API Framework plugin