Last active
March 18, 2022 15:47
-
-
Save jamesvidler/7570b11e44038dc24cc9eb08fa7786c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"strings" | |
) | |
type localization struct { | |
defaultLocale string | |
translations map[string]interface{} | |
} | |
func main() { | |
localization := getLocalization() | |
fmt.Println(localization) | |
} | |
func getLocalization() localization { | |
path := "./locales" | |
files := getFileNames(path) | |
translations := make(map[string]interface{}) | |
defaultLocale := "" | |
for _, fileName := range files { | |
data := getMapFromFile(fmt.Sprintf("locales/%s", fileName)) | |
locale := strings.Split(fileName, ".")[0] | |
if isDefaultLocale(fileName) { | |
defaultLocale = locale | |
} | |
translations[locale] = data | |
} | |
return localization{ | |
defaultLocale: defaultLocale, | |
translations: translations, | |
} | |
} | |
func getFileNames(folderPath string) []string { | |
files := []string{} | |
items, _ := ioutil.ReadDir(folderPath) | |
for _, item := range items { | |
if !item.IsDir() { | |
files = append(files, item.Name()) | |
} | |
} | |
return files | |
} | |
func getMapFromFile(filePath string) map[string]interface{} { | |
// Open our jsonFile | |
jsonFile, err := os.Open(filePath) | |
// if we os.Open returns an error then handle it | |
if err != nil { | |
fmt.Println(err) | |
} | |
// defer the closing of our jsonFile so that we can parse it later on | |
defer jsonFile.Close() | |
byteValue, _ := ioutil.ReadAll(jsonFile) | |
var result map[string]interface{} | |
json.Unmarshal([]byte(byteValue), &result) | |
return result | |
} | |
func isDefaultLocale(fileName string) bool { | |
return strings.Contains(fileName, ".default.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment