How do I convert a language code to its proper name in Go?

Viewed 183

I need to convert language codes like 'en-US' or 'ja' to their proper names like 'American English' and 'Japanese'. How do I do this?

1 Answers

I had some difficulty in finding this since the functionality is spread across 2 different packages - languages and display instead of being in one. Hope this helps someone who couldn't find out how to do this.

links to documentation:
https://pkg.go.dev/golang.org/x/text/language#CanonType.MustParse
https://pkg.go.dev/golang.org/x/text@v0.3.7/language/display#Namer

Sample Program:

package main

import (
    "fmt"
    "golang.org/x/text/language"
    "golang.org/x/text/language/display"
)

func main()  {
    japTag := language.MustParse("ja")
    fmt.Println(display.Self.Name(japTag))   // --> 日本語

    // To get the language names in English
    en := display.English.Languages()
    fmt.Println(en.Name(japTag))             // --> Japanese
}
Related