Package language provides HTTP middleware for parsing language from HTTP request and passing it via context.
Run the following command to install the package:
go get -u github.com/muonsoft/language
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/muonsoft/language"
)
func main() {
h := http.HandlerFunc(func (writer http.ResponseWriter, request *http.Request) {
tag := language.FromContext(request.Context())
fmt.Println("language:", tag)
})
m := language.NewMiddleware(h, language.SupportedLanguages(language.English, language.Russian))
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.Header.Set("Accept-Language", "ru")
w := httptest.NewRecorder()
m.ServeHTTP(w, r)
// Output: language: ru
}
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/muonsoft/language"
)
func main() {
h := http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
tag := language.FromContext(request.Context())
fmt.Println("language:", tag)
})
m := language.NewMiddleware(
h,
language.SupportedLanguages(language.English, language.Russian),
language.ReadFromCookie("lang"),
)
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.AddCookie(&http.Cookie{Name: "lang", Value: "ru"})
w := httptest.NewRecorder()
m.ServeHTTP(w, r)
// Output: language: ru
}