1
0

refactor: migrate utils in backend

This commit is contained in:
2026-07-15 10:53:24 +08:00
parent b3efb196ed
commit a8de650a5a
5 changed files with 150 additions and 42 deletions

View File

@@ -6,20 +6,22 @@ import (
"os"
)
// CLIArgs 保存从命令行解析得到的参数,对应旧后端 coconut-leaf.py 中 argparse 解析的结果。
// CLIArgs holds the arguments parsed from the command line, mirroring the
// argparse result in the legacy coconut-leaf.py.
type CLIArgs struct {
// Config 是 coconut-leaf 的配置文件路径(即旧后端的 CONFIG_TOML)。
// Config is the path to the configuration file (the legacy CONFIG_TOML).
Config string
// Init 指示是否在启动前初始化日历系统。
// Init indicates whether to initialize the calendar system before running.
Init bool
}
// ParseCLI 使用标准库 flag 包解析命令行参数并返回 *CLIArgs。
// 当必需的 --config 参数缺失时,打印用法并以退出码 2 退出(与 argparse 的退出码一致)。
// ParseCLI parses the command-line arguments via the standard flag package and
// returns a *CLIArgs. When the required --config flag is missing, it prints the
// usage and exits with status 2 (matching argparse's exit code).
func ParseCLI() *CLIArgs {
args := &CLIArgs{}
// 自定义用法输出,复刻旧后端 ArgumentParser description 横幅。
// Custom usage output mirroring the legacy ArgumentParser description banner.
flag.Usage = func() {
out := flag.CommandLine.Output()
fmt.Fprintln(out, "The server of light, self-host and multi-account calendar system.")
@@ -28,13 +30,13 @@ func ParseCLI() *CLIArgs {
flag.PrintDefaults()
}
// --config 对应旧后端的 -c/--config必需--init 对应旧后端的 -i/--init
// --config maps to the legacy -c/--config (required), --init to -i/--init.
flag.StringVar(&args.Config, "config", "", "The configuration file `CONFIG_TOML` for coconut-leaf")
flag.BoolVar(&args.Init, "init", false, "Set for initialize the calendar system")
flag.Parse()
// 标准库 flag 不支持 required故解析后手动校验。
// The standard flag package has no built-in "required", so validate manually.
if args.Config == "" {
fmt.Fprintln(os.Stderr, "error: the required flag --config is not provided")
flag.Usage()

View File

@@ -6,19 +6,20 @@ import (
"github.com/BurntSushi/toml"
)
// DatabaseDriver 表示配置文件中指定的数据库驱动类型,对应旧后端的 DatabaseDriver(StrEnum)。
// 用 const 配合 iota 模拟数值枚举,字符串形式由 databaseDriverFromString 转换。
// DatabaseDriver represents the database driver specified in the config file,
// mirroring the legacy DatabaseDriver(StrEnum). It is a numeric enum simulated
// with const + iota; its string form is produced by databaseDriverFromString.
type DatabaseDriver int
const (
// DatabaseDriverSqlite 表示使用 SQLite 数据库。
// DatabaseDriverSqlite means the SQLite database is used.
DatabaseDriverSqlite DatabaseDriver = iota
// DatabaseDriverMysql 表示使用 MySQL 数据库。
// DatabaseDriverMysql means the MySQL database is used.
DatabaseDriverMysql
)
// databaseDriverFromString 将配置文件中的 driver 字符串转换为 DatabaseDriver
// 无法识别的字符串将返回错误。
// databaseDriverFromString converts a driver string from the config file into a
// DatabaseDriver. An unrecognized string returns an error.
func databaseDriverFromString(s string) (DatabaseDriver, error) {
switch s {
case "sqlite":
@@ -30,78 +31,87 @@ func databaseDriverFromString(s string) (DatabaseDriver, error) {
}
}
// SqliteDatabaseConfig 是 SQLite 数据库的连接配置,对应旧后端 SqliteDatabaseConfig。
// SqliteDatabaseConfig is the connection config for SQLite, mirroring the
// legacy SqliteDatabaseConfig.
type SqliteDatabaseConfig struct {
// Path 是数据库文件的路径。
// Path is the database file path.
Path string `toml:"path"`
}
// MysqlDatabaseConfig 是 MySQL 数据库的连接配置,对应旧后端 MysqlDatabaseConfig。
// MysqlDatabaseConfig is the connection config for MySQL, mirroring the legacy
// MysqlDatabaseConfig.
type MysqlDatabaseConfig struct {
// Host 是数据库主机地址。
// Host is the database host.
Host string `toml:"host"`
// Port 是数据库端口。
// Port is the database port.
Port int `toml:"port"`
// User 是数据库用户名。
// User is the database user.
User string `toml:"user"`
// Password 是数据库密码。
// Password is the database password.
Password string `toml:"password"`
// Database 是数据库名称。
// Database is the database name.
Database string `toml:"database"`
}
// DatabaseConfig 描述数据库驱动及其对应的具体配置,对应旧后端 DatabaseConfig。
// 其中 Driver 起判别作用,决定 Sqlite 或 Mysql 中的哪一个被填充。
// DatabaseConfig describes the database driver and its concrete config, mirroring
// the legacy DatabaseConfig. Driver is the discriminator deciding whether Sqlite
// or Mysql is populated.
type DatabaseConfig struct {
// Driver 是当前选择的数据库驱动。
// Driver is the selected database driver.
Driver DatabaseDriver
// Sqlite Driver DatabaseDriverSqlite 时非空。
// Sqlite is non-nil when Driver is DatabaseDriverSqlite.
Sqlite *SqliteDatabaseConfig
// Mysql Driver DatabaseDriverMysql 时非空。
// Mysql is non-nil when Driver is DatabaseDriverMysql.
Mysql *MysqlDatabaseConfig
}
// WebConfig 是 Web 服务器的配置,对应旧后端 WebConfig
// WebConfig is the web server config, mirroring the legacy WebConfig.
type WebConfig struct {
// Port 是 Web 服务器监听端口。
// Port is the web server listening port.
Port int `toml:"port"`
}
// OthersConfig 是其余杂项配置,对应旧后端 OthersConfig
// OthersConfig holds miscellaneous options, mirroring the legacy OthersConfig.
type OthersConfig struct {
// Debug 指示是否启用调试模式。
// Debug indicates whether debug mode is enabled.
Debug bool `toml:"debug"`
// AutoTokenCleanDuration 是自动清理过期 token 的时间间隔(秒)。
// AutoTokenCleanDuration is the interval (in seconds) for auto-cleaning
// outdated tokens.
AutoTokenCleanDuration int `toml:"auto-token-clean-duration"`
}
// Config 是从配置文件解析得到的完整配置,对应旧后端 Config。
// Config is the full configuration parsed from the config file, mirroring the
// legacy Config.
type Config struct {
// Database 是数据库相关配置。
// Database is the database-related config.
Database DatabaseConfig
// Web 是 Web 服务器相关配置。
// Web is the web-server-related config.
Web WebConfig
// Others 是其余杂项配置。
// Others is the miscellaneous config.
Others OthersConfig
}
// rawDatabaseConfig 是仅用于 TOML 解析的内部结构。
// Config 字段以 toml.Primitive 暂存,以便依据 Driver 做两段式分发解码。
// rawDatabaseConfig is an internal struct used only for TOML decoding. Its
// Config field is stored as a toml.Primitive so it can be dispatched and decoded
// in two phases based on Driver.
type rawDatabaseConfig struct {
Driver string `toml:"driver"`
Config toml.Primitive `toml:"config"`
}
// rawConfig 是仅用于 TOML 解析的内部结构,配合两段式解码使用。
// rawConfig is an internal struct used only for TOML decoding, in tandem with
// the two-phase decode.
type rawConfig struct {
Database rawDatabaseConfig `toml:"database"`
Web WebConfig `toml:"web"`
Others OthersConfig `toml:"others"`
}
// LoadConfig 从给定路径读取并解析 TOML 配置文件,返回解析后的配置或错误。
// 它合并了旧后端的 setup_config 与 get_config第一阶段用 toml.DecodeFile 暂存 database.config
// 第二阶段依据 driver 用 PrimitiveDecode 分发解码到 SqliteDatabaseConfig 或 MysqlDatabaseConfig。
// LoadConfig reads and parses the TOML config file at the given path, returning
// the parsed config or an error. It merges the legacy setup_config and
// get_config: the first phase uses toml.DecodeFile to defer database.config, and
// the second phase dispatches PrimitiveDecode into SqliteDatabaseConfig or
// MysqlDatabaseConfig based on the driver.
func LoadConfig(path string) (*Config, error) {
var raw rawConfig
meta, err := toml.DecodeFile(path, &raw)

View File

@@ -19,6 +19,7 @@ require (
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect

View File

@@ -32,6 +32,8 @@ github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7Lk
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=

93
backend/utils.go Normal file
View File

@@ -0,0 +1,93 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
"github.com/google/uuid"
)
var (
usernamePattern = regexp.MustCompile(`^[0-9A-Za-z]+$`)
passwordPattern = regexp.MustCompile(`^[!-~]+$`)
)
// IsValidUsername reports whether s is a valid username.
func IsValidUsername(s string) bool {
return usernamePattern.MatchString(s)
}
// IsValidPassword reports whether s is a valid password.
func IsValidPassword(s string) bool {
return passwordPattern.MatchString(s)
}
// ComputePasswordHash returns the lowercased SHA-256 hex digest of password.
func ComputePasswordHash(password string) string {
sum := sha256.Sum256([]byte(password))
return hex.EncodeToString(sum[:])
}
// GenerateUUID returns a new UUID string, preferring version 1 (mirroring
// python's uuid.uuid1()), falling back to a random version-4 UUID on error.
func GenerateUUID() string {
u, err := uuid.NewUUID()
if err != nil {
u = uuid.New()
}
return u.String()
}
// GenerateToken returns a SHA-256 hex digest of the username concatenated with
// a fresh UUID.
func GenerateToken(username string) string {
sum := sha256.Sum256([]byte(username + GenerateUUID()))
return hex.EncodeToString(sum[:])
}
// GenerateSalt returns a random salt in the inclusive range [0, 6172748].
func GenerateSalt() int {
return rand.Intn(6172749)
}
// ComputePasswordHashWithSalt returns the lowercased SHA-256 hex digest of
// passwordHashed concatenated with the decimal string form of salt.
func ComputePasswordHashWithSalt(passwordHashed string, salt int) string {
sum := sha256.Sum256([]byte(passwordHashed + strconv.Itoa(salt)))
return hex.EncodeToString(sum[:])
}
// GetCurrentTimestamp returns the current UNIX timestamp in seconds.
func GetCurrentTimestamp() int {
return int(time.Now().Unix())
}
// GetTokenExpireOn returns the timestamp 2 days from now, used as the token
// expiry.
func GetTokenExpireOn() int {
return GetCurrentTimestamp() + 60*60*24*2
}
// Str2Bool reports whether s, compared case-insensitively, equals "true".
func Str2Bool(s string) bool {
return strings.ToLower(s) == "true"
}
// GCD returns the greatest common divisor of a and b via the Euclidean
// algorithm.
func GCD(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
// LCM returns the least common multiple of a and b.
func LCM(a, b int) int {
return (a * b) / GCD(a, b)
}