更新用法

This commit is contained in:
Yun
2024-08-11 22:19:28 +08:00
parent 8d3bd7cade
commit 3a4c3e58e6
4 changed files with 51 additions and 9 deletions
-2
View File
@@ -5,8 +5,6 @@ import (
) )
type LangError interface { type LangError interface {
NewError(ctx context.Context, key string) error // New错误
NewErrorFormat(ctx context.Context, key string, format map[string]string) error // New错误
Error() string // 实现error接口&获取翻译后的错误信息 Error() string // 实现error接口&获取翻译后的错误信息
GetCode() int // 获取翻译后的Code GetCode() int // 获取翻译后的Code
GetKey() string // 获取原Key值 GetKey() string // 获取原Key值
+44
View File
@@ -0,0 +1,44 @@
package main
import (
"context"
"github.com/yuninks/langx"
)
func main() {
err := ErrorWithMsg.Error()
// 输出:错误
println(err.Error())
}
type Language string
// 添加key+默认语言
func newLanguage(uniKey string, code int, defaultValue string) Language {
langx.AppendCode(map[string]int{uniKey: code})
langx.AppendTrans("zh_hans", map[string]string{uniKey: defaultValue})
return Language(uniKey)
}
func (l Language) String() string {
return string(l)
}
func (l Language) Error() error {
return langx.NewError(context.Background(), l.String())
}
func (l Language) Errorf(format map[string]string) error {
return langx.NewErrorFormat(context.Background(), l.String(), format)
}
var (
Success Language = newLanguage("success", 200, "成功")
Error Language = newLanguage("error", 400, "错误")
ErrorWithMsg Language = newLanguage("error_with_msg", 400, "错误 #msg#")
)
-7
View File
@@ -31,13 +31,6 @@ func init() {
} }
} }
// 设置
func InitLangx(ops ...Option) {
for _, opt := range ops {
opt(l.ops)
}
}
// 这是语言的Code // 这是语言的Code
func RegisterCode(datas map[string]int) { func RegisterCode(datas map[string]int) {
l.mut.Lock() l.mut.Lock()
+7
View File
@@ -16,6 +16,13 @@ func defaultOptions() *options {
} }
} }
// 设置
func InitLangx(ops ...Option) {
for _, opt := range ops {
opt(l.ops)
}
}
type Option func(*options) type Option func(*options)
// 设置默认的code // 设置默认的code