Idiomatic example of how to use Context.Negotiate with generic and custom MediaTypes
jarrodhroberson opened this issue · comments
It would be very helpful if someone could post an example of how to return different format responses based on the Request Accept header.
I have searched for a long time and can not find any examples of how to actually render a response based on the Accept header.
And definitely not how to render based on a custom MediaType that has an API version number in it ("application/vnd.health.json;version=1.0.0") or ("application/vnd.kliket.health+v1.json", )
Here is what I have figured out so far:
func Health(c *gin.Context) {
startupTime := c.MustGet("startupTime").(time.Time)
status := models.NewHealth(startupTime)
c.Negotiate(http.StatusOK, gin.Negotiate{
Offered: []string{"application/vnd.health.json;version=1.0.0", gin.MIMEJSON, gin.MIMEYAML, gin.MIMEXML, gin.MIMEHTML},
HTMLName: "",
HTMLData: status,
JSONData: status,
XMLData: status,
YAMLData: status,
Data: status,
})
}
I can get back all the formats but HTML and my custom versioned MediaType which is the preferred one.
I can not find any example of what should go in HTMLName
or how to register a Render for my custom MediaType.
I figured out through trial and error :-( that you have to load the html/templates with r.LoadHTMLGlob("web/html/*")
or r.LoadHTMLFiles()
and then put the JUST the filename of the html file/template you want in the HTMLName
value. This took a digging through the source and lots of searching to come up with a guess that this might work.