Files
nl-pms-api/internal/config/config.go
2026-08-15 07:41:11 +08:00

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