Grails - add header to every response

后端 未结 1 1173
南笙
南笙 2020-12-29 15:04

How could I add a response header - say X-Time that would look something like

X-Time: 112

Where the value given would be the time in milliseconds that the re

相关标签:
1条回答
  • 2020-12-29 15:30

    To simply add a header to the response, you can use an after Filter.

    // grails-app/conf/MyFilters.groovy
    class MyFilters {
        def filters = {
            addHeader(uri: '/*') {
                after = {
                    response.setHeader('X-Time', value)
                }
            }
        }
    }
    

    Edit:

    To actually compute the time, it'd probably be more proper to use a javax.servlet.Filter instead of a Grails filter.

    src/groovy/com/example/myproject/MyFilter.groovy

    package com.example.myproject
    
    import javax.servlet.*
    
    class MyFilter implements Filter {
    
        void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
    
            def start = System.currentTimeMillis()
            chain.doFilter(request, response)
    
            def elapsed = System.currentTimeMillis() - start
            response.setHeader('X-Time', elapsed as String)
        }
    
        void init(FilterConfig config) { }
        void destroy() { }
    }
    

    src/templates/war/web.xml (run grails install-templates if src/templates isn't already in your source tree)

    <filter>
      <filter-name>timer</filter-name>
      <filter-class>com.example.myproject.MyFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>timer</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    The reason for using the javax.servlet.Filter is so you don't have to separate out your "before" and "after" actions, and can therefore hold onto the start time throughout the entire filter chain & servlet execution.

    Supplementary note:

    To me, it seems strange to want to return the server elapsed execution time as a response header. Perhaps you have a decent reason for doing it, but in most cases I'd A) either be more concerned about total round-trip time (as observed by the client), or B) be logging elapsed execution times on the server for my own system administration/metrics purposes.

    0 讨论(0)
提交回复
热议问题