From 3a4c3e58e6d4adbeb99a2adba0fbde244e9c53fc Mon Sep 17 00:00:00 2001 From: Yun Date: Sun, 11 Aug 2024 22:19:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=94=A8=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- error.go | 2 -- example/enample2.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ langx.go | 7 ------- options.go | 7 +++++++ 4 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 example/enample2.go diff --git a/error.go b/error.go index b9aa56e..7abbb4e 100644 --- a/error.go +++ b/error.go @@ -5,8 +5,6 @@ import ( ) 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接口&获取翻译后的错误信息 GetCode() int // 获取翻译后的Code GetKey() string // 获取原Key值 diff --git a/example/enample2.go b/example/enample2.go new file mode 100644 index 0000000..ad4f45e --- /dev/null +++ b/example/enample2.go @@ -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#") +) diff --git a/langx.go b/langx.go index 81f5cb3..08a1996 100644 --- a/langx.go +++ b/langx.go @@ -31,13 +31,6 @@ func init() { } } -// 设置 -func InitLangx(ops ...Option) { - for _, opt := range ops { - opt(l.ops) - } -} - // 这是语言的Code func RegisterCode(datas map[string]int) { l.mut.Lock() diff --git a/options.go b/options.go index 9433b7e..1d69fae 100644 --- a/options.go +++ b/options.go @@ -16,6 +16,13 @@ func defaultOptions() *options { } } +// 设置 +func InitLangx(ops ...Option) { + for _, opt := range ops { + opt(l.ops) + } +} + type Option func(*options) // 设置默认的code