60 lines
1.8 KiB
Go
60 lines
1.8 KiB
Go
// Package config 负责加载并全局提供 config.yaml 中的配置
|
||
package config
|
||
|
||
import (
|
||
"fmt"
|
||
"os"
|
||
|
||
"gopkg.in/yaml.v3"
|
||
)
|
||
|
||
// LLMConf 单个大模型提供方的连接配置
|
||
type LLMConf struct {
|
||
APIKey string `yaml:"api_key"` // API 密钥(为空则该模型不可用,走规则 AI 兜底)
|
||
BaseURL string `yaml:"base_url"` // OpenAI 兼容接口的基础地址
|
||
Model string `yaml:"model"` // 模型名称(如 lite / deepseek-chat)
|
||
}
|
||
|
||
// Config 后端全部配置的根结构
|
||
type Config struct {
|
||
Server struct {
|
||
Port int `yaml:"port"` // HTTP 服务监听端口
|
||
} `yaml:"server"`
|
||
MySQL struct {
|
||
Host string `yaml:"host"` // 数据库主机
|
||
Port int `yaml:"port"` // 数据库端口
|
||
User string `yaml:"user"` // 数据库账号
|
||
Password string `yaml:"password"` // 数据库密码
|
||
Database string `yaml:"database"` // 库名
|
||
} `yaml:"mysql"`
|
||
JWT struct {
|
||
Secret string `yaml:"secret"` // JWT 签名密钥
|
||
ExpireHours int `yaml:"expire_hours"` // Token 有效期(小时)
|
||
} `yaml:"jwt"`
|
||
AI struct {
|
||
Spark LLMConf `yaml:"spark"` // 讯飞星火 Lite 配置
|
||
DeepSeek LLMConf `yaml:"deepseek"` // DeepSeek 配置
|
||
} `yaml:"ai"`
|
||
}
|
||
|
||
// C 全局配置实例(Load 成功后可直接读取)
|
||
var C Config
|
||
|
||
// Load 从指定路径读取 YAML 配置并解析到全局变量 C
|
||
func Load(path string) error {
|
||
data, err := os.ReadFile(path)
|
||
if err != nil {
|
||
return fmt.Errorf("读取配置文件失败: %w", err)
|
||
}
|
||
if err := yaml.Unmarshal(data, &C); err != nil {
|
||
return fmt.Errorf("解析配置文件失败: %w", err)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// DSN 拼接 GORM 使用的 MySQL 连接串
|
||
func (c *Config) DSN() string {
|
||
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=false&loc=Local",
|
||
c.MySQL.User, c.MySQL.Password, c.MySQL.Host, c.MySQL.Port, c.MySQL.Database)
|
||
}
|