Files
past-go/past-go/internal/config/config.go
T
2026-10-07 09:28:43 +08:00

91 lines
2.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package config 读取服务配置(对应 PHP 的 config.php + config.credentials.php)。
package config
import (
"fmt"
"os"
"path/filepath"
"gopkg.in/yaml.v3"
)
type Config struct {
Listen string `yaml:"listen"` // 监听地址,如 ":8080"
Debug bool `yaml:"debug"` // gin debug 模式(打印路由等)
// DataDir 运行数据目录:其下 uploads/ 存用户上传文件,data/ 存日志与缓存。
// 对应 PHP 的 backend/ 目录;默认为可执行文件所在目录。
DataDir string `yaml:"data_dir"`
DB struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Name string `yaml:"name"`
User string `yaml:"user"`
Pass string `yaml:"pass"`
} `yaml:"db"`
Wechat struct {
AppID string `yaml:"appid"`
Secret string `yaml:"secret"`
// 订阅消息模板 ID(对应 WECHAT_SUBSCRIBE_TEMPLATES['notify'])
NotifyTemplateID string `yaml:"notify_template_id"`
} `yaml:"wechat"`
TencentMapKey string `yaml:"tencent_map_key"`
// PHPCompat 对齐的 PHP 版本:"8.0"(默认,数据库数值按字符串返回)或 "8.1"(原生类型)
PHPCompat string `yaml:"php_compat"`
// MaxUploadMB 单文件上传上限(PHP: MAX_UPLOAD_SIZE = 50MB)
MaxUploadMB int64 `yaml:"max_upload_mb"`
// Notify 定时补发通知(对应 cron_notify.php)的执行间隔(分钟),0 表示关闭
NotifyIntervalMin int `yaml:"notify_interval_min"`
}
func Load(path string) (*Config, error) {
c := &Config{}
c.Listen = ":8080"
c.DB.Host = "127.0.0.1"
c.DB.Port = 3306
c.DB.Name = "past"
c.DB.User = "past"
c.MaxUploadMB = 50
c.NotifyIntervalMin = 5
c.Wechat.NotifyTemplateID = "tOaqM_Z6pNSih2pVpaUmP86MgwnDT5ZlwOqd0lgmXP8"
c.PHPCompat = "8.0"
b, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("读取配置文件 %s: %w", path, err)
}
if err := yaml.Unmarshal(b, c); err != nil {
return nil, fmt.Errorf("解析配置文件 %s: %w", path, err)
}
if c.DataDir == "" {
exe, err := os.Executable()
if err != nil {
return nil, err
}
c.DataDir = filepath.Dir(exe)
}
abs, err := filepath.Abs(c.DataDir)
if err != nil {
return nil, err
}
c.DataDir = abs
return c, nil
}
func (c *Config) UploadDir() string { return filepath.Join(c.DataDir, "uploads") }
func (c *Config) LogDir() string { return filepath.Join(c.DataDir, "data") }
func (c *Config) DSN() string {
// interpolateParams=true:统一走文本协议,所有列以字节返回,由 store 按列类型转换(对齐 PDO 行为)
// time_zone 会在驱动建立的每个 MySQL 连接上设置会话时区,保证 SQL NOW()/CURRENT_TIMESTAMP
// 与 Go 进程的 Asia/Shanghai 一致。使用固定 +08:00 不依赖 MySQL 时区表是否安装。
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=false&interpolateParams=true&loc=Local&time_zone=%%27%%2B08%%3A00%%27&multiStatements=false",
c.DB.User, c.DB.Pass, c.DB.Host, c.DB.Port, c.DB.Name)
}