I would like to convert locale tag to IETF standard. IETF language tag asserts en-US
as a correct tag for American English. In may case, it's possible that I would get en_US
as an input.
Currently I'm using this method:
func toLanguageTag(l string) string {
return strings.Replace(l, "_", "-", -1)
}
For example, I know that Java has toLanguageTag
method. Should I continue use this approach, or there is more preferable way to do what I want?
There's a package in the external packages repository of Go (maintained by the Go project but not part of the standard library), that handles parsing and validation of language tags.
https://godoc.org/golang.org/x/text/language
Example:
package main
import (
"fmt"
"golang.org/x/text/language"
)
func main() {
tag := language.Make("en_us")
fmt.Println(tag)
}
// Output: en-US
Note that language.Make()
omits the error in case of an invalid tag. You should use language.Parse()
which returns an error in practice.