1. 实现配置文件解析
2. 实现数据库连接
This commit is contained in:
94
internal/config/config.go
Normal file
94
internal/config/config.go
Normal file
@@ -0,0 +1,94 @@
|
||||
// Package config 提供配置文件读取和解析功能
|
||||
// 支持YAML格式的配置文件解析
|
||||
// 包含服务器和数据库相关配置
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
// Config 代表应用的完整配置结构
|
||||
type Config struct {
|
||||
// Server 服务器配置
|
||||
Server ServerConfig `yaml:"server"`
|
||||
|
||||
// Database 数据库配置
|
||||
Database DatabaseConfig `yaml:"database"`
|
||||
}
|
||||
|
||||
// ServerConfig 代表服务器配置
|
||||
type ServerConfig struct {
|
||||
// Host 服务器监听IP
|
||||
Host string `yaml:"host"`
|
||||
|
||||
// Port 服务器监听端口
|
||||
Port int `yaml:"port"`
|
||||
}
|
||||
|
||||
// DatabaseConfig 代表数据库配置
|
||||
type DatabaseConfig struct {
|
||||
// Host 数据库主机地址
|
||||
Host string `yaml:"host"`
|
||||
|
||||
// Port 数据库端口
|
||||
Port int `yaml:"port"`
|
||||
|
||||
// Username 数据库用户名
|
||||
Username string `yaml:"username"`
|
||||
|
||||
// Password 数据库密码
|
||||
Password string `yaml:"password"`
|
||||
|
||||
// DBName 数据库名称
|
||||
DBName string `yaml:"dbname"`
|
||||
|
||||
// SSLMode SSL模式
|
||||
SSLMode string `yaml:"sslmode"`
|
||||
|
||||
// MaxOpenConns 最大开放连接数
|
||||
MaxOpenConns int `yaml:"max_open_conns"`
|
||||
|
||||
// MaxIdleConns 最大空闲连接数
|
||||
MaxIdleConns int `yaml:"max_idle_conns"`
|
||||
|
||||
// ConnMaxLifetime 连接最大生命周期(秒)
|
||||
ConnMaxLifetime int `yaml:"conn_max_lifetime"`
|
||||
}
|
||||
|
||||
// NewConfig 创建并返回一个新的配置实例
|
||||
func NewConfig() *Config {
|
||||
return &Config{}
|
||||
}
|
||||
|
||||
// Load 从指定路径加载配置文件
|
||||
func (c *Config) Load(path string) error {
|
||||
// 读取配置文件
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read config file: %v", err)
|
||||
}
|
||||
|
||||
// 解析YAML配置
|
||||
if err := yaml.Unmarshal(data, c); err != nil {
|
||||
return fmt.Errorf("failed to parse config file: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDatabaseConnectionString 获取数据库连接字符串
|
||||
func (c *Config) GetDatabaseConnectionString() string {
|
||||
// 构建PostgreSQL连接字符串
|
||||
return fmt.Sprintf(
|
||||
"user=%s password=%s dbname=%s host=%s port=%d sslmode=%s",
|
||||
c.Database.Username,
|
||||
c.Database.Password,
|
||||
c.Database.DBName,
|
||||
c.Database.Host,
|
||||
c.Database.Port,
|
||||
c.Database.SSLMode,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user