2 Commits
Author SHA1 Message Date
yyc12345 1cc6b7b1ba refactor: use new struct in backend 2026-07-15 11:08:45 +08:00
yyc12345 a8de650a5a refactor: migrate utils in backend 2026-07-15 10:53:24 +08:00
8 changed files with 299 additions and 188 deletions
-45
View File
@@ -1,45 +0,0 @@
package main
import (
"flag"
"fmt"
"os"
)
// CLIArgs 保存从命令行解析得到的参数,对应旧后端 coconut-leaf.py 中 argparse 解析的结果。
type CLIArgs struct {
// Config 是 coconut-leaf 的配置文件路径(即旧后端的 CONFIG_TOML)。
Config string
// Init 指示是否在启动前初始化日历系统。
Init bool
}
// ParseCLI 使用标准库 flag 包解析命令行参数并返回 *CLIArgs。
// 当必需的 --config 参数缺失时,打印用法并以退出码 2 退出(与 argparse 的退出码一致)。
func ParseCLI() *CLIArgs {
args := &CLIArgs{}
// 自定义用法输出,复刻旧后端 ArgumentParser 的 description 横幅。
flag.Usage = func() {
out := flag.CommandLine.Output()
fmt.Fprintln(out, "The server of light, self-host and multi-account calendar system.")
fmt.Fprintln(out)
fmt.Fprintf(out, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
}
// --config 对应旧后端的 -c/--config(必需),--init 对应旧后端的 -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,故解析后手动校验。
if args.Config == "" {
fmt.Fprintln(os.Stderr, "error: the required flag --config is not provided")
flag.Usage()
os.Exit(2)
}
return args
}
+47
View File
@@ -0,0 +1,47 @@
package cli
import (
"flag"
"fmt"
"os"
)
// CLIArgs holds the arguments parsed from the command line, mirroring the
// argparse result in the legacy coconut-leaf.py.
type CLIArgs struct {
// Config is the path to the configuration file (the legacy CONFIG_TOML).
Config string
// Init indicates whether to initialize the calendar system before running.
Init bool
}
// Parse 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 Parse() *CLIArgs {
args := &CLIArgs{}
// 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.")
fmt.Fprintln(out)
fmt.Fprintf(out, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
}
// --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()
// 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()
os.Exit(2)
}
return args
}
-141
View File
@@ -1,141 +0,0 @@
package main
import (
"fmt"
"github.com/BurntSushi/toml"
)
// DatabaseDriver 表示配置文件中指定的数据库驱动类型,对应旧后端的 DatabaseDriver(StrEnum)。
// 用 const 配合 iota 模拟数值枚举,字符串形式由 databaseDriverFromString 转换。
type DatabaseDriver int
const (
// DatabaseDriverSqlite 表示使用 SQLite 数据库。
DatabaseDriverSqlite DatabaseDriver = iota
// DatabaseDriverMysql 表示使用 MySQL 数据库。
DatabaseDriverMysql
)
// databaseDriverFromString 将配置文件中的 driver 字符串转换为 DatabaseDriver
// 无法识别的字符串将返回错误。
func databaseDriverFromString(s string) (DatabaseDriver, error) {
switch s {
case "sqlite":
return DatabaseDriverSqlite, nil
case "mysql":
return DatabaseDriverMysql, nil
default:
return 0, fmt.Errorf("invalid database driver: %q", s)
}
}
// SqliteDatabaseConfig 是 SQLite 数据库的连接配置,对应旧后端 SqliteDatabaseConfig。
type SqliteDatabaseConfig struct {
// Path 是数据库文件的路径。
Path string `toml:"path"`
}
// MysqlDatabaseConfig 是 MySQL 数据库的连接配置,对应旧后端 MysqlDatabaseConfig。
type MysqlDatabaseConfig struct {
// Host 是数据库主机地址。
Host string `toml:"host"`
// Port 是数据库端口。
Port int `toml:"port"`
// User 是数据库用户名。
User string `toml:"user"`
// Password 是数据库密码。
Password string `toml:"password"`
// Database 是数据库名称。
Database string `toml:"database"`
}
// DatabaseConfig 描述数据库驱动及其对应的具体配置,对应旧后端 DatabaseConfig。
// 其中 Driver 起判别作用,决定 Sqlite 或 Mysql 中的哪一个被填充。
type DatabaseConfig struct {
// Driver 是当前选择的数据库驱动。
Driver DatabaseDriver
// Sqlite 在 Driver 为 DatabaseDriverSqlite 时非空。
Sqlite *SqliteDatabaseConfig
// Mysql 在 Driver 为 DatabaseDriverMysql 时非空。
Mysql *MysqlDatabaseConfig
}
// WebConfig 是 Web 服务器的配置,对应旧后端 WebConfig。
type WebConfig struct {
// Port 是 Web 服务器监听端口。
Port int `toml:"port"`
}
// OthersConfig 是其余杂项配置,对应旧后端 OthersConfig。
type OthersConfig struct {
// Debug 指示是否启用调试模式。
Debug bool `toml:"debug"`
// AutoTokenCleanDuration 是自动清理过期 token 的时间间隔(秒)。
AutoTokenCleanDuration int `toml:"auto-token-clean-duration"`
}
// Config 是从配置文件解析得到的完整配置,对应旧后端 Config。
type Config struct {
// Database 是数据库相关配置。
Database DatabaseConfig
// Web 是 Web 服务器相关配置。
Web WebConfig
// Others 是其余杂项配置。
Others OthersConfig
}
// rawDatabaseConfig 是仅用于 TOML 解析的内部结构。
// 其 Config 字段以 toml.Primitive 暂存,以便依据 Driver 做两段式分发解码。
type rawDatabaseConfig struct {
Driver string `toml:"driver"`
Config toml.Primitive `toml:"config"`
}
// rawConfig 是仅用于 TOML 解析的内部结构,配合两段式解码使用。
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。
func LoadConfig(path string) (*Config, error) {
var raw rawConfig
meta, err := toml.DecodeFile(path, &raw)
if err != nil {
return nil, err
}
driver, err := databaseDriverFromString(raw.Database.Driver)
if err != nil {
return nil, err
}
cfg := &Config{
Web: raw.Web,
Others: raw.Others,
Database: DatabaseConfig{
Driver: driver,
},
}
switch driver {
case DatabaseDriverSqlite:
var s SqliteDatabaseConfig
if err := meta.PrimitiveDecode(raw.Database.Config, &s); err != nil {
return nil, err
}
cfg.Database.Sqlite = &s
case DatabaseDriverMysql:
var m MysqlDatabaseConfig
if err := meta.PrimitiveDecode(raw.Database.Config, &m); err != nil {
return nil, err
}
cfg.Database.Mysql = &m
}
return cfg, nil
}
+151
View File
@@ -0,0 +1,151 @@
package config
import (
"fmt"
"github.com/BurntSushi/toml"
)
// 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 means the SQLite database is used.
DatabaseDriverSqlite DatabaseDriver = iota
// DatabaseDriverMysql means the MySQL database is used.
DatabaseDriverMysql
)
// 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":
return DatabaseDriverSqlite, nil
case "mysql":
return DatabaseDriverMysql, nil
default:
return 0, fmt.Errorf("invalid database driver: %q", s)
}
}
// SqliteDatabaseConfig is the connection config for SQLite, mirroring the
// legacy SqliteDatabaseConfig.
type SqliteDatabaseConfig struct {
// Path is the database file path.
Path string `toml:"path"`
}
// MysqlDatabaseConfig is the connection config for MySQL, mirroring the legacy
// MysqlDatabaseConfig.
type MysqlDatabaseConfig struct {
// Host is the database host.
Host string `toml:"host"`
// Port is the database port.
Port int `toml:"port"`
// User is the database user.
User string `toml:"user"`
// Password is the database password.
Password string `toml:"password"`
// Database is the database name.
Database string `toml:"database"`
}
// 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 is the selected database driver.
Driver DatabaseDriver
// Sqlite is non-nil when Driver is DatabaseDriverSqlite.
Sqlite *SqliteDatabaseConfig
// Mysql is non-nil when Driver is DatabaseDriverMysql.
Mysql *MysqlDatabaseConfig
}
// WebConfig is the web server config, mirroring the legacy WebConfig.
type WebConfig struct {
// Port is the web server listening port.
Port int `toml:"port"`
}
// OthersConfig holds miscellaneous options, mirroring the legacy OthersConfig.
type OthersConfig struct {
// Debug indicates whether debug mode is enabled.
Debug bool `toml:"debug"`
// AutoTokenCleanDuration is the interval (in seconds) for auto-cleaning
// outdated tokens.
AutoTokenCleanDuration int `toml:"auto-token-clean-duration"`
}
// Config is the full configuration parsed from the config file, mirroring the
// legacy Config.
type Config struct {
// Database is the database-related config.
Database DatabaseConfig
// Web is the web-server-related config.
Web WebConfig
// Others is the miscellaneous config.
Others OthersConfig
}
// 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 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"`
}
// Load 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 Load(path string) (*Config, error) {
var raw rawConfig
meta, err := toml.DecodeFile(path, &raw)
if err != nil {
return nil, err
}
driver, err := databaseDriverFromString(raw.Database.Driver)
if err != nil {
return nil, err
}
cfg := &Config{
Web: raw.Web,
Others: raw.Others,
Database: DatabaseConfig{
Driver: driver,
},
}
switch driver {
case DatabaseDriverSqlite:
var s SqliteDatabaseConfig
if err := meta.PrimitiveDecode(raw.Database.Config, &s); err != nil {
return nil, err
}
cfg.Database.Sqlite = &s
case DatabaseDriverMysql:
var m MysqlDatabaseConfig
if err := meta.PrimitiveDecode(raw.Database.Config, &m); err != nil {
return nil, err
}
cfg.Database.Mysql = &m
}
return cfg, nil
}
+1
View File
@@ -19,6 +19,7 @@ require (
github.com/go-playground/validator/v10 v10.30.1 // indirect github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // 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/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect
+2
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 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 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/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 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
+5 -2
View File
@@ -6,12 +6,15 @@ import (
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/yyc12345/coconut-leaf/backend/cli"
"github.com/yyc12345/coconut-leaf/backend/config"
) )
func main() { func main() {
args := ParseCLI() args := cli.Parse()
cfg, err := LoadConfig(args.Config) cfg, err := config.Load(args.Config)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
+93
View File
@@ -0,0 +1,93 @@
package utils
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)
}