From a08b9538ae21de1ec6ea81a4a2d0a10367c64162 Mon Sep 17 00:00:00 2001 From: xing Date: Thu, 1 Jun 2023 21:30:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/pkg/config/config.go | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/app/pkg/config/config.go b/app/pkg/config/config.go index 13a24e4..2d483e2 100644 --- a/app/pkg/config/config.go +++ b/app/pkg/config/config.go @@ -2,6 +2,7 @@ package config import ( "encoding/json" + "errors" "fmt" "github.com/fthvgb1/wp-go/safety" "gopkg.in/yaml.v2" @@ -109,24 +110,17 @@ func InitConfig(conf string) error { case ".yaml": err = yaml.Unmarshal(file, &c) case ".json": - var v map[string]any - err = json.Unmarshal(file, &v) - if err == nil { - marshal, er := yaml.Marshal(v) - if er != nil { - return er - } - err = yaml.Unmarshal(marshal, &c) - } + err = jsonToYaml(file, &c) default: err = yaml.Unmarshal(file, &c) if err == nil { break } - err = json.Unmarshal(file, &c) + err = jsonToYaml(file, &c) if err == nil { break } + return errors.Join(errors.New("can't parse the config"), err) } if err != nil { @@ -136,6 +130,20 @@ func InitConfig(conf string) error { return nil } +func jsonToYaml[T any](b []byte, c T) error { + var v map[string]any + err := json.Unmarshal(b, &v) + if err != nil { + return err + } + marshal, er := yaml.Marshal(v) + if er != nil { + return er + } + err = yaml.Unmarshal(marshal, c) + return err +} + type Dsn struct { Host string `yaml:"host" json:"host,omitempty"` Port json.Number `yaml:"port" json:"port,omitempty"`