Gin: [question] is it possible to rewrite the body in a middleware?

Created on 31 Mar 2016  路  7Comments  路  Source: gin-gonic/gin

Hi,

I'd like to make a middleware that detects if a jsonp response has been required ("callback=callbackValue" as query param) and if that is true, let the normal execution run and then capture the answer and rewrite it as jsonp (callbackValue(json)); I could not see a way to obtain the written body

Thanks

question

Most helpful comment

@Flonka, have a look at @jim3mar module. It shows perfectly how to handle this. You have to substitute the default writer with yours.

https://github.com/jim3mar/gin-jsonp/blob/master/jsonp.go#L30

var wb *responseBuffer
        if w, ok := c.Writer.(gin.ResponseWriter); ok {
            wb = NewResponseBuffer(w)
            c.Writer = wb
            c.Next()
        }else {
            c.Next()
            return
        }

// Do whatever you want with the response here...
        status := wb.status
        data := wb.Body.Bytes()
        wb.Body.Reset()

All 7 comments

@rodriguezgustavo
I have rewrited goware/jsonp into jim3mar/ginjsonp
You can try it!

the gin.Context struct have ResponseWriter var, we should catch it and rewrite it!

+1 , I was also curious if it was possible to read the currently written response body in a middleware.

@Flonka, have a look at @jim3mar module. It shows perfectly how to handle this. You have to substitute the default writer with yours.

https://github.com/jim3mar/gin-jsonp/blob/master/jsonp.go#L30

var wb *responseBuffer
        if w, ok := c.Writer.(gin.ResponseWriter); ok {
            wb = NewResponseBuffer(w)
            c.Writer = wb
            c.Next()
        }else {
            c.Next()
            return
        }

// Do whatever you want with the response here...
        status := wb.status
        data := wb.Body.Bytes()
        wb.Body.Reset()

@nazwa cheers!

try it:

      cb := c.Query("ballback")
      if cb != "" {
        c.Writer.Write([]byte(cb))
        c.Writer.Write([]byte("("))
      }
     c.Next()
     if cb != "" {
        c.Writer.Write([]byte(")"))
     }

@nazwa it not word now

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kekemuyu picture kekemuyu  路  3Comments

CodingPapi picture CodingPapi  路  3Comments

ghost picture ghost  路  3Comments

xpbliss picture xpbliss  路  3Comments

lilee picture lilee  路  3Comments