You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

49 lines
1.5 KiB

  1. // Copyright 2016 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 language_test
  5. import (
  6. "fmt"
  7. "net/http"
  8. "strings"
  9. "golang.org/x/text/language"
  10. )
  11. // matcher is a language.Matcher configured for all supported languages.
  12. var matcher = language.NewMatcher([]language.Tag{
  13. language.BritishEnglish,
  14. language.Norwegian,
  15. language.German,
  16. })
  17. // handler is a http.HandlerFunc.
  18. func handler(w http.ResponseWriter, r *http.Request) {
  19. t, q, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
  20. // We ignore the error: the default language will be selected for t == nil.
  21. tag, _, _ := matcher.Match(t...)
  22. fmt.Printf("%17v (t: %6v; q: %3v; err: %v)\n", tag, t, q, err)
  23. }
  24. func ExampleParseAcceptLanguage() {
  25. for _, al := range []string{
  26. "nn;q=0.3, en-us;q=0.8, en,",
  27. "gsw, en;q=0.7, en-US;q=0.8",
  28. "gsw, nl, da",
  29. "invalid",
  30. } {
  31. // Create dummy request with Accept-Language set and pass it to handler.
  32. r, _ := http.NewRequest("GET", "example.com", strings.NewReader("Hello"))
  33. r.Header.Set("Accept-Language", al)
  34. handler(nil, r)
  35. }
  36. // Output:
  37. // en-GB (t: [ en en-US nn]; q: [ 1 0.8 0.3]; err: <nil>)
  38. // en-GB-u-rg-uszzzz (t: [ gsw en-US en]; q: [ 1 0.8 0.7]; err: <nil>)
  39. // de (t: [ gsw nl da]; q: [ 1 1 1]; err: <nil>)
  40. // en-GB (t: []; q: []; err: language: tag is not well-formed)
  41. }