...

Source file src/golang.org/x/text/language/httpexample_test.go

Documentation: golang.org/x/text/language

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

View as plain text