123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- package main
- import (
- "encoding/json"
- "flag"
- "fmt"
- "go-msa-auth/config"
- "go-msa-auth/internal/models"
- "go-msa-auth/server"
- "io/fs"
- "log"
- "os"
- "path/filepath"
- )
- func main() {
- // 检查子命令
- if len(os.Args) < 2 {
- fmt.Println("Expected 'server' or 'import' subcommands")
- os.Exit(1)
- }
- switch os.Args[1] {
- case "server":
- runServer()
- case "import":
- runImport()
- default:
- fmt.Println("Unknown subcommand:", os.Args[1])
- os.Exit(1)
- }
- }
- func runServer() {
- // 启动服务器逻辑
- config.InitConfig()
- if err := server.InitServer(); err != nil {
- log.Fatal("Failed to start server:", err)
- }
- }
- func runImport() {
- // 定义命令行参数
- importCmd := flag.NewFlagSet("import", flag.ExitOnError)
- dirPath := importCmd.String("dir", "./data/json_files", "Path to the directory containing JSON files")
- if err := importCmd.Parse(os.Args[2:]); err != nil {
- log.Fatal("Failed to parse flags:", err)
- }
- // 检查目录是否存在
- if _, err := os.Stat(*dirPath); os.IsNotExist(err) {
- log.Fatalf("The specified directory does not exist: %s", *dirPath)
- }
- // 初始化数据库
- models.InitDatabase("auth.db")
- // 遍历目录中的 JSON 文件
- err := filepath.WalkDir(*dirPath, func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- // 只处理 .json 文件
- if !d.IsDir() && filepath.Ext(path) == ".json" {
- log.Printf("Processing file: %s", path)
- if err := importJSONFile(path); err != nil {
- log.Printf("Failed to import file %s: %v", path, err)
- } else {
- log.Printf("Successfully imported file: %s", path)
- }
- }
- return nil
- })
- if err != nil {
- log.Fatalf("Error while traversing directory: %v", err)
- }
- log.Println("All files have been processed!")
- }
- // importJSONFile 处理单个 JSON 文件的导入逻辑
- func importJSONFile(filePath string) error {
- // 读取 JSON 文件
- data, err := os.ReadFile(filePath)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", filePath, err)
- }
- // 解析 JSON 文件内容
- var importData models.LicenseImportData
- if err := json.Unmarshal(data, &importData); err != nil {
- return fmt.Errorf("failed to parse file %s: %w", filePath, err)
- }
- // 打印导入信息
- log.Printf("Importing licenses for app: %s, name: %s, expire_time: %s",
- importData.AppID, importData.Name, importData.ExpireTime)
- // 遍历授权码并写入数据库
- for _, license := range importData.Licenses {
- authCode := &models.AuthCode{
- UUID: license.UUID,
- DeviceID: license.LicenseFile, // 假设 LicenseFile 存储为 DeviceID
- }
- // 保存到数据库
- if err := models.SaveAuthCode(authCode); err != nil {
- log.Printf("Failed to save license with UUID %s: %v", license.UUID, err)
- } else {
- log.Printf("Successfully imported license: %s", license.UUID)
- }
- }
- return nil
- }
|