gin icon indicating copy to clipboard operation
gin copied to clipboard

Don't allow to override response header

Open ri8ika opened this issue 2 years ago • 2 comments

I have a specific situation where I don't want to let developer override response header if the header key matched.

So, whenever developer overrides response header supposedly like this:

router.GET("/:id", func(ctx *gin.Context) {
   ctx.Header("Content-Type", "application/json") // should panic or just do not set it.
   ctx.Header("X-Any-Other-Header", "other header") // Okay set it.
   // ...
}

I want to allow setting of any header is okay but setting of specific header should panic. In this case the header is "Content-Type". So, application should result in panic or just do not set it.

Is there a way to achieve this? I couldn't think of a solution because middleware runs first and this GET func runs later.

ri8ika avatar May 10 '23 10:05 ri8ika

Found a way to solve this:

https://github.com/gin-gonic/gin/issues/2748#issuecomment-1485713004

ri8ika avatar May 10 '23 12:05 ri8ika

Re-opening this issue because code using afterMiddlewareWriter as in the linked issue returns gin default status code and not able to set my own. Thus, looking for better alternative to this.

ri8ika avatar May 11 '23 17:05 ri8ika