Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created November 17, 2016 16:17
Show Gist options
  • Save hnakamur/92d283d5700507cc2a0df7bb1401478a to your computer and use it in GitHub Desktop.
Save hnakamur/92d283d5700507cc2a0df7bb1401478a to your computer and use it in GitHub Desktop.
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
Copy link
Author

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