Compare commits

...

16 Commits

Author SHA1 Message Date
yun 4edb2d244e 去掉Error接口的封装,另起一个仓库 2025-10-26 20:31:38 +08:00
yun 914a74d05e 修改初始化 2025-10-26 16:15:42 +08:00
yun 8aaf4fe712 Merge branch 'master' into dev 2025-10-26 15:52:32 +08:00
yun 38a46b85e1 更新一些设计 2025-10-26 15:41:30 +08:00
Yun 7ac8c24d2a 优化错误方法的封装 2025-08-22 14:23:30 +08:00
Yun 175e36ebd7 优化一下锁的使用 2025-04-14 17:03:32 +08:00
yun 046091cb35 更新 2024-11-10 22:55:35 +08:00
yun 7eaf21634c 优化逻辑 2024-11-10 22:28:02 +08:00
yun f66e76883f 允许获取当前默认的语言 2024-08-11 23:35:18 +08:00
yun 3a4c3e58e6 更新用法 2024-08-11 22:19:28 +08:00
yun 8d3bd7cade 修改错误接口的方法 2024-07-31 16:47:23 +08:00
yun ea8d17943d 优化Error的封装 2024-07-24 19:47:00 +08:00
yun d9fdeabf85 修复在append的时候会有panic问题 2024-07-24 19:36:32 +08:00
yun d710d6b30c 添加锁 避免panic 2024-07-21 11:10:41 +08:00
yun 5205a6cad1 更新 2024-07-11 21:12:01 +08:00
yun 2bed4e7fca 支持embed的文件 2024-07-11 13:47:21 +08:00
10 changed files with 188 additions and 170 deletions
+35
View File
@@ -0,0 +1,35 @@
package langx
import "context"
const ctxLangKey string = "ctxLang"
func SetCtxLang(ctx context.Context, lang string) context.Context {
return context.WithValue(ctx, ctxLangKey, lang)
}
func GetCtxLang(ctx context.Context) string {
// 指定的
lang := ctx.Value(ctxLangKey)
l := ""
if lang != nil {
l = lang.(string)
}
// HTTP头部的
if l == "" {
lang = ctx.Value("Accept-Language")
if lang != nil {
l = lang.(string)
}
}
// 默认的
if l == "" {
l = GetDefaultLang()
}
return l
}
-58
View File
@@ -1,58 +0,0 @@
package langx
import (
"context"
)
type LangError struct {
ctx context.Context
key string
format map[string]string
}
type errorConst string
const errorLang errorConst = "errorLang"
func (e *LangError) Error() string {
errLang := e.ctx.Value(errorLang)
l := ""
if errLang != nil {
l = string(errLang.(errorConst))
}
return GetFormat(l, e.key, e.format)
}
func (e *LangError) GetCode() int {
return GetCode(e.key)
}
func (e *LangError) GetMsg() string {
return e.key
}
func (e *LangError) GetFormat() map[string]string {
if e.format == nil {
e.format = make(map[string]string)
}
return e.format
}
func NewErrorFormat(ctx context.Context, key string, format map[string]string) error {
return &LangError{
ctx: ctx,
key: key,
format: format,
}
}
func NewError(ctx context.Context, key string) error {
return &LangError{
ctx: ctx,
key: key,
}
}
func SetCtxLang(ctx context.Context, lang string) context.Context {
return context.WithValue(ctx, errorLang, lang)
}
-52
View File
@@ -1,52 +0,0 @@
package langx_test
import (
"context"
"testing"
"github.com/yuninks/langx"
)
func TestError(t *testing.T) {
var err error
ctx := context.Background()
langx.InitLangx(
langx.SetDefaultCode(0),
langx.SetDefaultLanguage("zh"),
)
langx.RegisterCode(map[string]int{
"login_success": 200,
"error": 400,
"username": 201,
})
langx.RegisterTrans("zh", map[string]string{
"login_success": "成功",
"error": "错误",
"username": "你好 #name#", // 有占位符
})
langx.RegisterTrans("en", map[string]string{
"login_success": "success",
"error": "error",
"username": "Hello #name#", // 有占位符
})
err = langx.NewError(ctx, "error")
// fmt.Printf("err: %v\n", err)
t.Log(err.Error())
val, ok := err.(*langx.LangError)
if ok {
t.Log(val.GetCode())
}
err = langx.NewErrorFormat(ctx, "username", map[string]string{
"name": "yuninks",
})
t.Log(err.Error())
val, ok = err.(*langx.LangError)
if ok {
t.Log(val.GetCode())
}
}
-4
View File
@@ -1,4 +0,0 @@
{
"success":200,
"error":400
}
-4
View File
@@ -1,4 +0,0 @@
{
"success":"Success",
"error":"Error #msg#"
}
-4
View File
@@ -1,4 +0,0 @@
{
"success":"成功",
"error":"失败 #msg#"
}
-18
View File
@@ -1,18 +0,0 @@
package main
import (
"fmt"
"github.com/yuninks/langx"
)
func main() {
langx.RegisterDir("./lang")
code, msg := langx.GetTransFormat("zh", "success", map[string]string{})
fmt.Println(code, msg)
code, msg = langx.GetTransFormat("en", "error", map[string]string{
"msg": "这是失败的原因",
})
fmt.Println(code, msg)
}
+134 -22
View File
@@ -2,48 +2,76 @@ package langx
import (
"context"
"embed"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
)
type langx struct {
ops *options
codeMap map[string]int
transMap map[string]map[string]string
mut sync.RWMutex
}
var l *langx = &langx{}
func init() {
l = &langx{
ops: defaultOptions(),
codeMap: make(map[string]int),
transMap: make(map[string]map[string]string),
}
}
// 设置
func InitLangx(ops ...Option) {
for _, opt := range ops {
opt(l.ops)
}
var l *langx = &langx{
ops: defaultOptions(),
codeMap: make(map[string]int),
transMap: make(map[string]map[string]string),
mut: sync.RWMutex{},
}
// 这是语言的Code
func RegisterCode(datas map[string]int) {
l.mut.Lock()
defer l.mut.Unlock()
if datas == nil {
datas = make(map[string]int)
}
l.codeMap = datas
}
// 追加覆盖Code
func AppendCode(datas map[string]int) {
l.mut.Lock()
defer l.mut.Unlock()
if datas == nil {
datas = make(map[string]int)
}
if l.codeMap == nil {
l.codeMap = map[string]int{}
}
for k, v := range datas {
l.codeMap[k] = v
}
}
// 注册语言翻译
func RegisterTrans(langName string, trans map[string]string) {
l.mut.Lock()
defer l.mut.Unlock()
l.transMap[langName] = trans
}
// 追加覆盖翻译
func AppendTrans(langName string, trans map[string]string) {
l.mut.Lock()
defer l.mut.Unlock()
for k, v := range trans {
if l.transMap[langName] == nil {
l.transMap[langName] = map[string]string{}
}
l.transMap[langName][k] = v
}
}
// 直接读取文件夹获取配置
// 要求:
// 1.json格式文件
@@ -83,14 +111,90 @@ func RegisterDir(dir string) error {
return nil
})
// code文件为状态码,其他为对应的语言文件,文件名为语言名
return err
}
func RegisterEmbed(asset embed.FS) error {
paths, err := readEmbedAllPath(asset, "")
if err != nil {
panic(err)
return err
}
for _, ff := range paths {
// 获取文件的后缀
fileName := strings.Replace(ff.path, ".json", "", 1)
if fileName == "code" {
data := map[string]int{}
err = json.Unmarshal(ff.datas, &data)
if err != nil {
return err
}
RegisterCode(data)
} else {
data := map[string]string{}
err = json.Unmarshal(ff.datas, &data)
if err != nil {
return err
}
RegisterTrans(fileName, data)
}
}
// code文件为状态码,其他为对应的语言文件,文件名为语言名
return nil
}
type fileData struct {
path string
datas []byte
}
func readEmbedAllPath(asset embed.FS, path string) ([]fileData, error) {
newRoot := ""
if path == "" {
newRoot = "."
} else {
newRoot = path
}
fs, err := asset.ReadDir(newRoot)
if err != nil {
return nil, err
}
var files []fileData
for _, f := range fs {
if f.IsDir() {
chaild := ""
if newRoot == "." {
chaild = f.Name()
} else {
chaild = newRoot + "/" + f.Name()
}
df, err := readEmbedAllPath(asset, chaild)
if err != nil {
return nil, err
}
files = append(files, df...)
continue
}
by, err := asset.ReadFile(newRoot + "/" + f.Name())
if err != nil {
return nil, err
}
ff := fileData{
path: f.Name(),
datas: by,
}
files = append(files, ff)
}
return files, nil
}
// 获取翻译
// 包含Code和Message
func GetTransFormat(lang string, key string, format map[string]string) (code int, str string) {
@@ -113,6 +217,8 @@ func GetTransFormatCtx(ctx context.Context, key string, format map[string]string
// 根据Key获取code
func GetCode(key string) int {
l.mut.RLock()
defer l.mut.RUnlock()
code, ok := l.codeMap[key]
if !ok {
return l.ops.defaultCode
@@ -122,6 +228,8 @@ func GetCode(key string) int {
// 获取翻译
func GetMsg(lang string, key string) string {
l.mut.RLock()
defer l.mut.RUnlock()
// 找指定语言
str, ok := l.transMap[lang]
if ok {
@@ -165,11 +273,15 @@ func GetDefaultCode() int {
return l.ops.defaultCode
}
// 获取默认语言
func GetDefaultLang() string {
return l.ops.defaultLang
}
func getLangFromCtx(ctx context.Context) string {
ctxVal := ctx.Value(l.ops.ctxLangKey)
lang := l.ops.defaultLang
if ctxVal != nil {
lang = ctxVal.(string)
lang := GetCtxLang(ctx)
if lang == "" {
lang = l.ops.defaultLang
}
return lang
}
+14 -7
View File
@@ -4,7 +4,7 @@ type options struct {
defaultCode int
defaultLang string
replaceKey string
ctxLangKey string
// ctxLangKey string
}
func defaultOptions() *options {
@@ -12,7 +12,14 @@ func defaultOptions() *options {
defaultCode: 200,
defaultLang: "zh",
replaceKey: "#%s#",
ctxLangKey: "language",
// ctxLangKey: "language",
}
}
// 设置
func InitLangx(ops ...Option) {
for _, opt := range ops {
opt(l.ops)
}
}
@@ -26,11 +33,11 @@ func SetDefaultCode(code int) Option {
}
// 从ctx里面获取语言的key
func SetCtxLangKey(key string) Option {
return func(o *options) {
o.ctxLangKey = key
}
}
// func SetCtxLangKey(key string) Option {
// return func(o *options) {
// o.ctxLangKey = key
// }
// }
// 默认语言
func SetDefaultLanguage(lang string) Option {
+5 -1
View File
@@ -1,5 +1,9 @@
# 简介
这是简单的一个多语言响应工具
这是简单的一个多语言响应工具,能够通过多种方式加载资源文件,然后进行匹配。同时支持占位符替换的形式在多语言响应的时候替换特定字符,让响应更友好。
# 使用方法
看example