Home > Mobile >  Render JSON with custom Content-Type in Gin
Render JSON with custom Content-Type in Gin

Time:07-21

I want to know if it is possible to add a "method" to Gin's context to add the header Content-Type: application/hal json instead of doing it in all API calls SetHeader.

Something like this:

ctx.HALJSON(http.StatusOK, hal)

CodePudding user response:

You can use c.Render with a custom renderer, that implements render.Renderer.

If the actual rendering is identical to JSON (HAL should be) you can embed render.JSON into your struct, so that the method Render(http.ResponseWriter) error comes for free, and then implement only the custom content type:

type HALJSON struct {
    render.JSON
}

func (HALJSON) WriteContentType(w http.ResponseWriter) {
    header := w.Header()
    if val := header["Content-Type"]; len(val) == 0 {
        header["Content-Type"] = []string{"application/hal json"}
    }
}

And then use it as such:

func MyHandler(c *gin.Context) {
    // handler code...
    c.Render(http.StatusOK, HALJSON{})
}
  • Related