github 地址的链接:go语言的学习使用
package cacheimport ("database/sql""fmt""go_dome/config""log"_ "github.com/go-sql-driver/mysql"
)var DB *sql.DBfunc InitMySQL() {cfg := config.AppConfig.MySQLdsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.Database)var err errorDB, err = sql.Open("mysql", dsn)if err != nil {log.Fatalf("Failed to connect to MySQL: %v", err)}if err := DB.Ping(); err != nil {log.Fatalf("Failed to ping MySQL: %v", err)}log.Println("Connected to MySQL!")
}
package cacheimport ("context""fmt""go_dome/config""github.com/redis/go-redis/v9"
)var RedisClient *redis.Client
var Ctx = context.Background()func InitRedis() {cfg := config.AppConfig.RedisRedisClient = redis.NewClient(&redis.Options{Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),Password: cfg.Password,DB: cfg.DB,})if _, err := RedisClient.Ping(Ctx).Result(); err != nil {panic(fmt.Sprintf("Failed to connect to Redis: %v", err))}
}
package configimport ("log""os""gopkg.in/yaml.v2"
)type Config struct {Server struct {Port int `yaml:"port"`} `yaml:"server"`MySQL struct {Host string `yaml:"host"`Port int `yaml:"port"`Username string `yaml:"username"`Password string `yaml:"password"`Database string `yaml:"database"`} `yaml:"mysql"`Redis struct {Host string `yaml:"host"`Port int `yaml:"port"`Password string `yaml:"password"`DB int `yaml:"db"`} `yaml:"redis"`
}var AppConfig Configfunc LoadConfig() {file, err := os.Open("config/config.yaml")if err != nil {log.Fatalf("Error opening config file: %v", err)}defer file.Close()decoder := yaml.NewDecoder(file)if err := decoder.Decode(&AppConfig); err != nil {log.Fatalf("Error decoding config file: %v", err)}
}
剩下的我将把代码放上去,给予链接