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

Walkthrough

Space play step click any line
Three takeaways
  1. 1The x/text language matcher turns a fuzzy Accept-Language header into one of your supported locales instead of forcing an exact match.
  2. 2Formatting money correctly means pairing a locale-aware printer with the right currency unit, not just prepending a symbol.
  3. 3Gin's Negotiate lets one handler serve JSON, XML, or YAML based on what the client asks for.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Locale-aware pricing in a Gin handler — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code