Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example Go web app which prints localized messages
package main
import (
"context"
"html"
"log"
"net/http"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
func main() {
http.HandleFunc("/", withMessagePrinter(func(w http.ResponseWriter, r *http.Request) {
p := getMessagePrinter(r)
p.Fprintf(w, "Hello, %[1]q", html.EscapeString(r.URL.Path))
}))
log.Fatal(http.ListenAndServe(":8080", nil))
}
func withMessagePrinter(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
t, _, _ := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
tag, _, _ := matcher.Match(t...)
p := message.NewPrinter(tag)
ctx := context.WithValue(context.Background(), messagePrinterKey, p)
next.ServeHTTP(w, r.WithContext(ctx))
}
}
func getMessagePrinter(r *http.Request) *message.Printer {
return r.Context().Value(messagePrinterKey).(*message.Printer)
}
// NOTE: This code is based on
// https://github.com/golang/proposal/blob/master/design/12750-localization.md#example-statically-linked-package
// and the example at
// https://godoc.org/golang.org/x/text/language#ParseAcceptLanguage
func init() {
for _, e := range entries {
for _, t := range e.entry {
message.SetString(e.lang, t.key, t.value)
}
}
langs := make([]language.Tag, 0, len(entries))
langs = append(langs, language.English)
for _, e := range entries {
langs = append(langs, e.lang)
}
matcher = language.NewMatcher(langs)
}
type entry struct {
key string
value string
}
var entries = []struct {
lang language.Tag
entry []entry
}{
{
language.Japanese, []entry{
{"Hello, %[1]q", "こんにちは、%[1]q"},
},
},
}
var matcher language.Matcher
type contextKey int
const (
messagePrinterKey contextKey = iota + 1
)
@hnakamur

This comment has been minimized.

Copy link
Owner Author

hnakamur commented Nov 17, 2016

Run the server.

go run main.go

An example session using curl.

$ curl localhost:8080          
Hello, "/"
$ curl -H 'Accept-Language: ja' localhost:8080
こんにちは、"/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.