Description
Description
I am creating a middleware function, and I want to modify the json that is sent back after the handler function is run. The thing is that, that json could be created in different ways:
c.IndentedJSON(http.StatusOK, body)
c.JSON(http.StatusOK, body)
...
In my middleware function, I would like to modify that json, and return it with the same "rendering" it was created, so, as an example, if it was using the indented json, I want to modify the json e.g, by wrapping it in another json, but return it in indented json format too, as it was originally written in the handler function.
How to reproduce
package main
import (
"github.com/gin-gonic/gin"
)
func myMiddleware(c *gin.Context) {
// do something here with the json response
}
func main() {
g := gin.Default()
g.Use(myMiddleware)
g.GET("/hello/:name", func(c *gin.Context) {
body := map[string]string{"name": "Manuel", "surname":"gin"}
c.IndentedJSON(200, body)
})
g.Run(":9000")
}
Expectations
So in case that the middleware wraps the response, I would expect something like:
$ curl http://localhost:9000/hello/world
{
"data": {
"name": "Manuel",
"surname": "gin"
}
}
Actual result
$ curl -i http://localhost:9000/hello/world
{"data": {"name":"Manuel","surname": "gin"}}
Because I don't know how it was "rendered", I assumed it was using the normal c.JSON
Environment
- go version: 1.23
- gin version (or commit ref):
- operating system: windows
Comment
Would it make sense to add a key in the context specifying what render was used?
Something like:
c.Set("gin:render", "indentedJSON")