我想知道是否可以在 Gin 的上下文中添加一個“方法”來添加標頭Content-Type: application/hal+json,而不是在所有 API 調用中都這樣做SetHeader。是這樣的:ctx.HALJSON(http.StatusOK, hal)
1 回答

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
您可以使用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) {
// handler code...
c.Render(http.StatusOK, HALJSON{})
}
- 1 回答
- 0 關注
- 209 瀏覽
添加回答
舉報
0/150
提交
取消