go
35 lines · 4 steps
Content negotiation in Gin handlers
A single Gin handler serves the same product as JSON or XML by honoring the client's Accept header.
Explained by
highlit
1package handlers
2
3import (
4 "net/http"
5
6 "github.com/gin-gonic/gin"
7)
8
9type Product struct {
10 XMLName struct{} `json:"-" xml:"product"`
11 ID int `json:"id" xml:"id"`
12 Name string `json:"name" xml:"name"`
13 Price float64 `json:"price" xml:"price"`
14 Tags []string `json:"tags" xml:"tags>tag"`
15}
16
17func GetProduct(c *gin.Context) {
18 id := c.Param("id")
19
20 product, err := productStore.FindByID(c.Request.Context(), id)
21 if err != nil {
22 c.Negotiate(http.StatusNotFound, gin.Negotiate{
23 Offered: []string{gin.MIMEJSON, gin.MIMEXML},
24 Data: gin.H{"error": "product not found"},
25 })
26 return
27 }
28
29 c.Negotiate(http.StatusOK, gin.Negotiate{
30 Offered: []string{gin.MIMEJSON, gin.MIMEXML},
31 Data: product,
32 JSONData: product,
33 XMLData: product,
34 })
35}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Content negotiation lets one endpoint respond in multiple formats based on the client's Accept header.
- 2Dual struct tags let the same Go type serialize cleanly to both JSON and XML.
- 3Offering a consistent format list on both success and error keeps negotiated responses uniform.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/content-negotiation-in-gin-handlers-explained-go-f917/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.