优化 yaml本身就兼容json....

This commit is contained in:
xing 2023-06-01 22:46:46 +08:00
parent a08b9538ae
commit e4fa93e893

View File

@ -2,14 +2,12 @@ package config
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"github.com/fthvgb1/wp-go/safety" "github.com/fthvgb1/wp-go/safety"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"io" "io"
"net/http" "net/http"
"os" "os"
"path/filepath"
"strings" "strings"
"time" "time"
) )
@ -106,23 +104,7 @@ func InitConfig(conf string) error {
return err return err
} }
var c Config var c Config
switch strings.ToLower(filepath.Ext(conf)) { err = yaml.Unmarshal(file, &c)
case ".yaml":
err = yaml.Unmarshal(file, &c)
case ".json":
err = jsonToYaml(file, &c)
default:
err = yaml.Unmarshal(file, &c)
if err == nil {
break
}
err = jsonToYaml(file, &c)
if err == nil {
break
}
return errors.Join(errors.New("can't parse the config"), err)
}
if err != nil { if err != nil {
return err return err
} }
@ -145,12 +127,12 @@ func jsonToYaml[T any](b []byte, c T) error {
} }
type Dsn struct { type Dsn struct {
Host string `yaml:"host" json:"host,omitempty"` Host string `yaml:"host" json:"host,omitempty"`
Port json.Number `yaml:"port" json:"port,omitempty"` Port string `yaml:"port" json:"port,omitempty"`
Db string `yaml:"db" json:"db,omitempty"` Db string `yaml:"db" json:"db,omitempty"`
User string `yaml:"user" json:"user,omitempty"` User string `yaml:"user" json:"user,omitempty"`
Password string `yaml:"password" json:"password,omitempty"` Password string `yaml:"password" json:"password,omitempty"`
Charset string `yaml:"charset" json:"charset,omitempty"` Charset string `yaml:"charset" json:"charset,omitempty"`
} }
func (m Dsn) GetDsn() string { func (m Dsn) GetDsn() string {