Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fallback when loading lang file #67

Merged
merged 1 commit into from
Oct 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lang/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@ package lang

import (
"errors"
"go/build"
"io/ioutil"
"os"
"path/filepath"
)

// LoadLocaleText will load the translations from the locale json files according to the locale
func LoadLocaleText(l string) ([]byte, error) {
lText, err := ioutil.ReadFile("./lang/" + l + ".json")
if os.IsNotExist(err) {
gopath := os.Getenv("GOPATH")
if gopath == "" {
gopath = build.Default.GOPATH
}
lPath := filepath.Join(gopath, "src", "github.com", "uniplaces", "carbon", "lang", l + ".json")
lText, err = ioutil.ReadFile(lPath)
}

if err != nil {
return nil, errors.New("not able to read the lang file:" + err.Error())
}
Expand Down
8 changes: 8 additions & 0 deletions translator_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package carbon

import (
"strings"
"testing"
"time"

Expand All @@ -18,3 +19,10 @@ func TestTrans(t *testing.T) {
c.SetLocale("pt")
assert.Equal(t, "pt", c.GetLocale())
}

func TestLoadNonExistentResource(t *testing.T) {
tr := NewTranslator()
err := tr.loadResource("iv")
assert.NotNil(t, err)
assert.True(t, strings.Contains(err.Error(), "github.com"))
}