Search code examples
grailsgroovygrails-controller

how to set the controller to respond as plain text in Grails


I need to create an API for monitoring and for that need that the response will be plain text , not json or xml

What I did is:

checked my application yaml that it contains text:

 types:
        all: '*/*'
        atom: application/atom+xml
        css: text/css
        csv: text/csv
        excel: application/vnd.ms-excel
        xlsx: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        form: application/x-www-form-urlencoded
        html:
          - text/html
          - application/xhtml+xml
        js: text/javascript
        json:
          - application/json
          - text/json
        multipartForm: multipart/form-data
        pdf: application/pdf
        rss: application/rss+xml
        text: text/plain
        hal:
          - application/hal+json
          - application/hal+xml
        xml:
          - text/xml
          - application/xml

added to my controller: static responseFormats = ['all'], tried also static responseFormats = ['text']

in my method did:

respond mystring, formats:['text']

But still grails trying to convert it to JSON and throwing http 406 error

How can I configure my controller to work with plain text

Thanks


Solution

  • I figure out how to do it i used render instead of respond in my method which solved the problem, still not sure why it is not possible with respond

    class MonitorApi4Controller {
    
       static responseFormats = ['text']
       static allowedMethods = [ monitorScrape: "GET"]
    
       MonitorService getMonitorService(){
           return ApplicationContextHolder.getBean('monitorService')
       }
    
       def monitorScrape(){
           def message = getMonitorService().serviceMethod()
           render message
       }
    }