在Gin中以自定义Content-Type渲染JSON

huangapple go评论76阅读模式
英文:

Render JSON with custom Content-Type in Gin

问题

我想知道是否可以在Gin的上下文中添加一个"方法",以便在所有API调用的地方添加头部Content-Type: application/hal+json,而不是使用SetHeader方法。

类似于这样的写法:

ctx.HALJSON(http.StatusOK, hal)
英文:

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)

答案1

得分: 1

你可以使用c.Render和自定义渲染器一起使用,该渲染器实现了render.Renderer接口。

如果实际渲染与JSON相同(HAL应该是),你可以将render.JSON嵌入到你的结构体中,这样Render(http.ResponseWriter) error方法就会自动实现,然后只需实现自定义的内容类型:

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"}
    }
}

然后可以这样使用:

func MyHandler(c *gin.Context) {
    // 处理程序代码...
    c.Render(http.StatusOK, HALJSON{})
}
英文:

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{})
}

huangapple
  • 本文由 发表于 2022年7月21日 04:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/73057913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定