Last active
August 29, 2015 13:57
-
-
Save goinggo/9417459 to your computer and use it in GitHub Desktop.
Localization With go-i18n
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
// RetrieveStation handles the example 2 tab. | |
func (buoyController *BuoyController) RetrieveStation() { | |
params := struct { | |
StationId string `form:"stationId" error:"invalid_station_id" valid:"Required"` | |
}{} | |
if buoyController.ParseAndValidate(¶ms) == false { | |
return | |
} | |
... | |
} |
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
// The localize package provides support for handling different languages | |
// and cultures. | |
package localize | |
import ( | |
"encoding/json" | |
"github.com/nicksnyder/go-i18n/i18n" | |
"github.com/nicksnyder/go-i18n/i18n/locale" | |
"github.com/nicksnyder/go-i18n/i18n/translation" | |
) | |
var ( | |
// T is the translate function for the specified user | |
// locale and default locale specified during the load. | |
T i18n.TranslateFunc | |
) | |
// Init initializes the local environment. | |
func Init(defaultLocale string) error { | |
switch defaultLocale { | |
case "en-US": | |
LoadJSON(defaultLocale, En_US) | |
default: | |
return fmt.Errorf("Unsupported Locale: %s", defaultLocale) | |
} | |
// Obtain the default translation function for use. | |
var err error | |
T, err = NewTranslation(defaultLocale) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
// NewTranslation obtains a translation function object for the | |
// specified locales. | |
func NewTranslation(userLocale string (t i18n.TranslateFunc, err error) { | |
t, err = i18n.Tfunc(userLocale) | |
if err != nil { | |
return t, err | |
} | |
return t, err | |
} | |
// LoadJSON takes a json document of translations and manually | |
// loads them into the system. | |
func LoadJSON(userLocale string, translationDocument string) error { | |
tranDocuments := []map[string]interface{}{} | |
err := json.Unmarshal([]byte(translationDocument), &tranDocuments) | |
if err != nil { | |
return err | |
} | |
for _, tranDocument := range tranDocuments { | |
tran, err := translation.NewTranslation(tranDocument) | |
if err != nil { | |
return err | |
} | |
i18n.AddTranslation(locale.MustNew(userLocale), tran) | |
} | |
return nil | |
} |
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
// en-US.go provides the localized messages for English in the United States. | |
package localize | |
var En_US = `[ | |
{ | |
"id": "invalid_credentials", | |
"translation": "Invalid Credentials were supplied." | |
}, | |
{ | |
"id": "application_error", | |
"translation": "An Application Error has occured." | |
}, | |
{ | |
"id": "invalid_station_id", | |
"translation": "Invalid Station Id Or Missing" | |
} | |
]` |
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
// ParseAndValidate will run the params through the validation framework and then | |
// response with the specified localized or provided message | |
func (baseController *BaseController) ParseAndValidate(params interface{}) bool { | |
err := baseController.ParseForm(params) | |
if err != nil { | |
baseController.ServeError(err) | |
return false | |
} | |
valid := validation.Validation{} | |
ok, err := valid.Valid(params) | |
if err != nil { | |
baseController.ServeError(err) | |
return false | |
} | |
if ok == false { | |
// Build a map of the error messages for each field | |
messages2 := map[string]string{} | |
val := reflect.ValueOf(params).Elem() | |
for i := 0; i < val.NumField(); i++ { | |
// Look for an error tag in the field | |
typeField := val.Type().Field(i) | |
tag := typeField.Tag | |
tagValue := tag.Get("error") | |
// Was there an error tag | |
if tagValue != "" { | |
messages2[typeField.Name] = tagValue | |
} | |
} | |
// Build the error response | |
errors := []string{} | |
for _, err := range valid.Errors { | |
// Match an error from the validation framework errors | |
// to a field name we have a mapping for | |
message, ok := messages2[err.Field] | |
if ok == true { | |
// Use a localized message if one exists | |
errors = append(errors, localize.T(message)) | |
continue | |
} | |
// No match, so use the message as is | |
errors = append(errors, err.Message) | |
} | |
baseController.ServeValidationErrors(errors) | |
return false | |
} | |
return true | |
} |
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
=== RUN TestMissingStation-8 | |
TRACE: 2014/03/07 17:13:50 mongo.go:186: Unknown : CopySession : Started : UseSession[monotonic] | |
TRACE: 2014/03/07 17:13:50 mongo.go:200: Unknown : CopySession : Completed | |
TRACE: 2014/03/07 17:13:50 baseController.go:52: Unknown : BaseController.Prepare : Info : UserId[Unknown] Path[/buoy/station/420] | |
TRACE: 2014/03/07 17:13:50 baseController.go:64: Unknown : Finish : Completed : /buoy/station/420 | |
TRACE: 2014/03/07 17:13:50 mongo.go:240: Unknown : CloseSession : Started | |
TRACE: 2014/03/07 17:13:50 mongo.go:244: Unknown : CloseSession : Completed | |
TRACE: 2014/03/07 17:13:50 buoyEndpoints_test.go:103: testing : TestStation : Info : Code[409] | |
{ | |
"errors": [ | |
"Invalid Station Id Or Missing" | |
] | |
} | |
Subject: Test Station Endpoint | |
Status Code Should Be 409 ✔ | |
The Result Should Not Be Empty ✔ | |
There Should Be An Error In The Result ✔ | |
9 assertions thus far | |
--- PASS: TestMissingStation-8 (0.00 seconds) |
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
[ | |
{ | |
"id": "d_days", | |
"translation": { | |
"one": "{{.Count}} day", | |
"other": "{{.Count}} days" | |
} | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a missing parenthesis on
localization_full.go
at line 40. Cheers!