// LoadLocales for globalization support func LoadLocales(path string) error { log.WithFields(log.Fields{ "path": path, }).Info("Loading language files from directory") filenames, err := filepath.Glob(path + "/*.json") if err != nil { return err } for _, filename := range filenames { filename, err = filepath.Abs(filename) if err != nil { return err } log.WithFields(log.Fields{ "path": filename, }).Debug("Loading locale") if err = i18n.LoadTranslationFile(filename); err != nil { return err } } return nil }
/** Clean language buffer with sending empty file For example it can be needed on deleting language or more **/ func (c *Lang) cleanLang(code string) error { s := c.langFileName("tmp_dir", code) err := ioutil.WriteFile(s, []byte("[]"), 0600) if err != nil { return err } defer os.Remove(s) return i18n.LoadTranslationFile(s) }
/** Try to receive sended via post file and apply it to language by param code returns error if occured by validation or adding to translations **/ func (c *Lang) applyFile(code string) (error, string) { _, header, err := c.GetFile("file") if err != nil { return err, T("lang_nofile") } a := strings.Split(header.Filename, ".") if l := len(a); l < 2 || strings.ToLower(a[l-1]) != "json" { return errors.New("client validation by file type hacked"), T("lang_badfile") } s := c.langFileName("tmp_dir", code) err = c.SaveToFile("file", s) if err != nil { return err, T("internal") } err = i18n.LoadTranslationFile(s) defer os.Remove(s) if err != nil { return err, T("internal") } s2 := c.langFileName("lang::folder", code) err = c.SaveToFile("file", s2) if err == nil { err = i18n.LoadTranslationFile(s2) } if err != nil { return err, T("internal") } return nil, "" }
func (c *Lang) Add() { l := &M.Lang{} err := c.ParseForm(l) if err != nil { beego.Error(err) c.Redirect(beego.UrlFor("Lang.Index"), 302) return } v := M.Validate(l) if v.HasErrors() { c.Index() c.Data["code"] = l.Code c.TplNames = "lang/index.tpl" M.ExpandFormErrors(&v, c.Data) return } err, msg := c.applyFile(l.Code) flash := beego.NewFlash() if err != nil { if DM.Find(l, M.Sf{"Code"}, M.Where{And: M.W{"Code": l.Code}}) != nil { err := i18n.LoadTranslationFile(c.langFileName("lang::folder", l.Code)) if err != nil { beego.Error(err) } } beego.Error(err) flash.Notice(msg) flash.Store(&c.Controller) c.Redirect(beego.UrlFor("Lang.Index"), 302) return } code := l.Code if DM.Find(l, M.Sf{"Id", "Code"}, M.Where{And: M.W{"Code": l.Code, "Active": true}, Or: M.W{"Code": l.Code, "Active": false}}) == nil { if !l.Active { l.Active = true _, err = DM.Update(l, "Active") } } else { l.Code = code v, err = DM.Insert(l, "Code") } if err != nil { beego.Error(err) if err := c.cleanLang(l.Code); err != nil { beego.Error(err) } flash.Notice(T("internal")) flash.Store(&c.Controller) } c.Redirect(beego.UrlFor("Lang.Index"), 302) }