优化从文件读取

This commit is contained in:
Yun
2024-07-10 17:24:58 +08:00
parent 3e2c5daf3e
commit 9d844ed7d4
7 changed files with 97 additions and 4 deletions
+4
View File
@@ -0,0 +1,4 @@
{
"success":200,
"error":400
}
+4
View File
@@ -0,0 +1,4 @@
{
"success":"Success",
"error":"Error #msg#"
}
+4
View File
@@ -0,0 +1,4 @@
{
"success":"成功",
"error":"失败 #msg#"
}
+18
View File
@@ -0,0 +1,18 @@
package main
import (
"fmt"
"github.com/yuninks/langx"
)
func main() {
langx.RegisterDir("./lang")
code, msg := langx.GetTrans("zh", "success", map[string]string{})
fmt.Println(code, msg)
code, msg = langx.GetTrans("en", "error", map[string]string{
"msg":"这是失败的原因",
})
fmt.Println(code, msg)
}
+53 -3
View File
@@ -2,7 +2,11 @@ package langx
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
)
@@ -16,10 +20,8 @@ var l *langx = &langx{}
func init() {
o := defaultOptions()
l = &langx{
ops: o,
ops: defaultOptions(),
codeMap: make(map[string]int),
transMap: make(map[string]map[string]string),
}
@@ -42,6 +44,54 @@ func RegisterTrans(langName string, trans map[string]string) {
l.transMap[langName] = trans
}
// 直接读取文件夹获取配置
// 要求:
// 1.json格式文件
// 2.code.json为自定义响应码 格式map[string]int{}
// 3.其他的json文件为对应语音 格式map[string]string{}
// 4.如果json解析错误将会panic
func RegisterDir(dir string) error {
// 遍历dir获取.json的文件
err := filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if strings.HasSuffix(info.Name(), ".json") {
// 读取文件
fileName := strings.Replace(info.Name(), ".json", "", 1)
by, err := os.ReadFile(path)
if err != nil {
return err
}
if fileName == "code" {
data := map[string]int{}
err = json.Unmarshal(by, &data)
if err != nil {
return err
}
RegisterCode(data)
} else {
data := map[string]string{}
err = json.Unmarshal(by, &data)
if err != nil {
return err
}
RegisterTrans(fileName, data)
}
}
return nil
})
if err != nil {
panic(err)
}
// code文件为状态码,其他为对应的语言文件,文件名为语言名
return nil
}
// 获取翻译
// 包含Code和Message
func GetTrans(lang string, key string, format map[string]string) (code int, str string) {
+12
View File
@@ -6,11 +6,23 @@ import (
"github.com/yuninks/langx"
)
const(
Lang string = "s"
)
var MapCode = map[string]int{
Lang:200,
}
func TestLangx(t *testing.T) {
langx.InitLangx(
langx.SetDefaultCode(0),
langx.SetDefaultLanguage("zh"),
)
langx.RegisterCode(map[string]int{
"login_success": 200,
"error": 400,
+2 -1
View File
@@ -18,6 +18,7 @@ func defaultOptions() *options {
type Option func(*options)
// 设置默认的code
func SetDefaultCode(code int) Option {
return func(o *options) {
o.defaultCode = code
@@ -38,7 +39,7 @@ func SetDefaultLanguage(lang string) Option {
}
}
// 替换规则 %s 为占位符
// 替换规则 %s 为占位符 需要填进去
func SetReplaceKey(key string) Option {
return func(o *options) {
o.replaceKey = key