初始化

This commit is contained in:
李琦
2026-08-15 07:41:11 +08:00
commit d9475ac9da
18 changed files with 1109 additions and 0 deletions

62
internal/config/config.go Normal file
View File

@@ -0,0 +1,62 @@
package config
import (
"errors"
"fmt"
"os"
"strings"
"gopkg.in/yaml.v3"
)
// Config 是服务的全部运行配置,来自 YAML 文件(默认 ./config.yaml可用 -config 指定)。
type Config struct {
// Env 为 dev 时启动执行 AutoMigrate其余一律视为 prod绝不执行 DDL。
Env string `yaml:"env"`
Listen string `yaml:"listen"`
// BaseURL 拼接文件访问 URL 的前缀(客户端可达的地址);留空则按请求 Host 推断。
BaseURL string `yaml:"base_url"`
// APIKey 是客户端上传凭证:请求需带 Authorization: Bearer <api_key>。
APIKey string `yaml:"api_key"`
StorageDir string `yaml:"storage_dir"`
MaxUploadMB int64 `yaml:"max_upload_mb"`
MySQL struct {
DSN string `yaml:"dsn"`
} `yaml:"mysql"`
}
// MaxUploadBytes 返回单文件字节上限。
func (c *Config) MaxUploadBytes() int64 { return c.MaxUploadMB << 20 }
// Load 读取并校验配置缺省值prod / :8788 / ./uploads / 20MB。
func Load(path string) (*Config, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("读取配置失败: %w", err)
}
c := &Config{}
if err := yaml.Unmarshal(b, c); err != nil {
return nil, fmt.Errorf("解析配置失败: %w", err)
}
if c.Env != "dev" {
c.Env = "prod"
}
if strings.TrimSpace(c.Listen) == "" {
c.Listen = ":8788"
}
if strings.TrimSpace(c.StorageDir) == "" {
c.StorageDir = "./uploads"
}
if c.MaxUploadMB <= 0 {
c.MaxUploadMB = 20
}
c.BaseURL = strings.TrimRight(strings.TrimSpace(c.BaseURL), "/")
c.APIKey = strings.TrimSpace(c.APIKey)
if c.APIKey == "" {
return nil, errors.New("配置缺少 api_key客户端上传凭证不允许留空开放上传")
}
if strings.TrimSpace(c.MySQL.DSN) == "" {
return nil, errors.New("配置缺少 mysql.dsn")
}
return c, nil
}