|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
_ "github.com/spf13/viper/remote"
|
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
func GetConsulConfig(url string, fileKey string) (*viper.Viper, error) {
|
|
|
|
conf := viper.New()
|
|
|
|
conf.AddRemoteProvider("consul", url, fileKey)
|
|
|
|
conf.SetConfigType("json")
|
|
|
|
err := conf.ReadRemoteConfig()
|
|
|
|
if err != nil {
|
|
|
|
log.Println("viper conf err :", err)
|
|
|
|
} else {
|
|
|
|
log.Println("viper conf :", conf)
|
|
|
|
}
|
|
|
|
return conf, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
{
|
|
|
|
"host": "192.168.137.131",
|
|
|
|
"port": "3306",
|
|
|
|
"user": "root",
|
|
|
|
"pwd": "mashibing123",
|
|
|
|
"database": "user_center"
|
|
|
|
}
|
|
|
|
**/
|
|
|
|
|
|
|
|
// type MySQLConfig struct {
|
|
|
|
// Host string `json:"host"`
|
|
|
|
// Post string `json:"port"`
|
|
|
|
// User string `json:"user"`
|
|
|
|
// Pwd string `json:"pwd"`
|
|
|
|
// Database string `json:"database"`
|
|
|
|
// }
|
|
|
|
|
|
|
|
func GetMysqlFromConsul(vip *viper.Viper) (db *gorm.DB, err error) {
|
|
|
|
newLogger := logger.New(
|
|
|
|
log.New(os.Stdout, "\r\n", log.LstdFlags),
|
|
|
|
logger.Config{
|
|
|
|
SlowThreshold: time.Second,
|
|
|
|
LogLevel: logger.Info,
|
|
|
|
Colorful: true,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
str := vip.GetString("user") + ":" + vip.GetString("pwd") + "@tcp(" + vip.GetString("host") + ":" + vip.GetString("port") + ")/" + vip.GetString("database") + "?charset=utf8mb4&parseTime=True&loc=Local"
|
|
|
|
db, errr := gorm.Open(mysql.Open(str), &gorm.Config{Logger: newLogger}) //"root:mashibing123@tcp(8.142.25.43:3306)/user_center?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{Logger: newLogger})
|
|
|
|
if errr != nil {
|
|
|
|
log.Println("db err :", errr)
|
|
|
|
}
|
|
|
|
|
|
|
|
return db, nil
|
|
|
|
}
|