Skip to content

Commit e96e984

Browse files
cxlblmnodivbyzero
andauthored
Add translation example (#1394)
Co-authored-by: nodivbyzero <nodivbyzero@gmail.com>
1 parent 5b31512 commit e96e984

File tree

1 file changed

+62
-0
lines changed
  • _examples/http-transalations

1 file changed

+62
-0
lines changed

_examples/http-transalations/main.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"net/http"
7+
"strings"
8+
9+
"github.com/go-playground/locales/en"
10+
"github.com/go-playground/locales/zh"
11+
"github.com/go-playground/locales/zh_Hant_TW"
12+
ut "github.com/go-playground/universal-translator"
13+
"github.com/go-playground/validator/v10"
14+
en_translations "github.com/go-playground/validator/v10/translations/en"
15+
zh_translations "github.com/go-playground/validator/v10/translations/zh"
16+
zh_tw_translations "github.com/go-playground/validator/v10/translations/zh_tw"
17+
)
18+
19+
var uni *ut.UniversalTranslator
20+
21+
// This example showcases how to use the Validator and UniversalTranslator with both Simplified and Traditional Chinese languages.
22+
// To run the example:
23+
// Step 1: go run _examples/http-transalations/main.go
24+
// Step 2 - Simplified Chinese: curl -d '{"first_name":"foo"}' -H "Accept-Language: zh" -H "Content-Type: application/json" -X POST http://localhost:8081/users
25+
// Step 3 - Traditional Chinese: curl -d '{"first_name":"foo"}' -H "Accept-Language: zh-Hant-TW" -H "Content-Type: application/json" -X POST http://localhost:8081/users
26+
func main() {
27+
validate := validator.New()
28+
en := en.New()
29+
uni = ut.New(en, en, zh.New(), zh_Hant_TW.New())
30+
31+
validate = validator.New()
32+
enTrans, _ := uni.GetTranslator("en")
33+
en_translations.RegisterDefaultTranslations(validate, enTrans)
34+
zhTrans, _ := uni.GetTranslator("zh")
35+
zh_translations.RegisterDefaultTranslations(validate, zhTrans)
36+
zhHantTrans, _ := uni.GetTranslator("zh_Hant_TW")
37+
zh_tw_translations.RegisterDefaultTranslations(validate, zhHantTrans)
38+
39+
type User struct {
40+
FirstName string `json:"first_name" validate:"required"`
41+
LastName string `json:"last_name" validate:"required"`
42+
}
43+
44+
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
45+
// ... fill user value
46+
var user User
47+
48+
// Header Accept-Language value is en or zh
49+
trans, _ := uni.GetTranslator(strings.Replace(r.Header.Get("Accept-Language"), "-", "_", -1))
50+
if err := validate.Struct(&user); err != nil {
51+
var errs validator.ValidationErrors
52+
var httpErrors []validator.ValidationErrorsTranslations
53+
if errors.As(err, &errs) {
54+
httpErrors = append(httpErrors, errs.Translate(trans))
55+
}
56+
r, _ := json.Marshal(httpErrors)
57+
w.Write(r)
58+
}
59+
})
60+
61+
http.ListenAndServe(":8081", nil)
62+
}

0 commit comments

Comments
 (0)