go
66 lines · 9 steps
Locale-aware pricing in a Gin handler
A Gin endpoint negotiates the client's language, converts a price into the matching currency, and renders it in the format that locale expects.
Explained by
highlit
1package handlers
2
3import (
4 "net/http"
5 "strings"
6
7 "github.com/gin-gonic/gin"
8 "golang.org/x/text/currency"
9 "golang.org/x/text/language"
10 "golang.org/x/text/message"
11)
12
13var localeCurrency = map[language.Tag]currency.Unit{
14 language.AmericanEnglish: currency.USD,
15 language.BritishEnglish: currency.GBP,
16 language.German: currency.EUR,
17 language.Japanese: currency.JPY,
18}
19
20var matcher = language.NewMatcher([]language.Tag{
21 language.AmericanEnglish,
22 language.BritishEnglish,
23 language.German,
24 language.Japanese,
25})
26
27type PriceView struct {
28 Locale string `json:"locale"`
29 Currency string `json:"currency"`
30 Amount string `json:"amount"`
31 Raw int64 `json:"raw_minor_units"`
32}
33
34func (h *Catalog) ShowPrice(c *gin.Context) {
35 product, err := h.products.Find(c.Param("sku"))
36 if err != nil {
37 c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "unknown sku"})
38 return
39 }
40
41 tag, _ := language.MatchStrings(matcher, c.GetHeader("Accept-Language"))
42 base, _ := tag.Base()
43 cur := localeCurrency[tag]
44
45 minor, err := h.rates.Convert(product.PriceUSD, cur)
46 if err != nil {
47 c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "rate unavailable"})
48 return
49 }
50
51 p := message.NewPrinter(tag)
52 formatted := p.Sprint(currency.Symbol(cur.Amount(float64(minor) / 100)))
53
54 view := PriceView{
55 Locale: strings.ToLower(base.String()),
56 Currency: cur.String(),
57 Amount: formatted,
58 Raw: minor,
59 }
60
61 c.Negotiate(http.StatusOK, gin.Negotiate{
62 Offered: []string{gin.MIMEJSON, gin.MIMEXML, gin.MIMEYAML},
63 Data: view,
64 HTMLName: "price.tmpl",
65 })
66}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The x/text language matcher turns a fuzzy Accept-Language header into one of your supported locales instead of forcing an exact match.
- 2Formatting money correctly means pairing a locale-aware printer with the right currency unit, not just prepending a symbol.
- 3Gin's Negotiate lets one handler serve JSON, XML, or YAML based on what the client asks for.
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
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
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 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/locale-aware-pricing-in-a-gin-handler-explained-go-d3dd/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.