63 lines
1.8 KiB
Go
63 lines
1.8 KiB
Go
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
|
||
}
|