examples_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package message_test
  5. import (
  6. "fmt"
  7. "net/http"
  8. "golang.org/x/text/language"
  9. "golang.org/x/text/message"
  10. )
  11. func Example_http() {
  12. // languages supported by this service:
  13. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  14. lang, _ := r.Cookie("lang")
  15. accept := r.Header.Get("Accept-Language")
  16. fallback := "en"
  17. tag := message.MatchLanguage(lang.String(), accept, fallback)
  18. p := message.NewPrinter(tag)
  19. p.Fprintln(w, "User language is", tag)
  20. })
  21. }
  22. func ExamplePrinter_numbers() {
  23. for _, lang := range []string{"en", "de", "de-CH", "fr", "bn"} {
  24. p := message.NewPrinter(language.Make(lang))
  25. p.Printf("%-6s %g\n", lang, 123456.78)
  26. }
  27. // Output:
  28. // en 123,456.78
  29. // de 123.456,78
  30. // de-CH 123’456.78
  31. // fr 123 456,78
  32. // bn ১,২৩,৪৫৬.৭৮
  33. }
  34. func ExamplePrinter_mVerb() {
  35. message.SetString(language.Dutch, "You have chosen to play %m.", "U heeft ervoor gekozen om %m te spelen.")
  36. message.SetString(language.Dutch, "basketball", "basketbal")
  37. message.SetString(language.Dutch, "hockey", "ijshockey")
  38. message.SetString(language.Dutch, "soccer", "voetbal")
  39. message.SetString(language.BritishEnglish, "soccer", "football")
  40. for _, sport := range []string{"soccer", "basketball", "hockey"} {
  41. for _, lang := range []string{"en", "en-GB", "nl"} {
  42. p := message.NewPrinter(language.Make(lang))
  43. fmt.Printf("%-6s %s\n", lang, p.Sprintf("You have chosen to play %m.", sport))
  44. }
  45. fmt.Println()
  46. }
  47. // Output:
  48. // en You have chosen to play soccer.
  49. // en-GB You have chosen to play football.
  50. // nl U heeft ervoor gekozen om voetbal te spelen.
  51. //
  52. // en You have chosen to play basketball.
  53. // en-GB You have chosen to play basketball.
  54. // nl U heeft ervoor gekozen om basketbal te spelen.
  55. //
  56. // en You have chosen to play hockey.
  57. // en-GB You have chosen to play hockey.
  58. // nl U heeft ervoor gekozen om ijshockey te spelen.
  59. }