Repository: hujinbo23/dst-admin-go Branch: main Commit: 065fa628fcac Files: 151 Total size: 1.0 MB Directory structure: gitextract_5gwete13/ ├── .claude/ │ └── skills/ │ ├── api-generator/ │ │ └── SKILL.md │ ├── find-skills/ │ │ └── SKILL.md │ ├── go-concurrency-patterns/ │ │ └── SKILL.md │ ├── golang-patterns/ │ │ └── SKILL.md │ ├── golang-pro/ │ │ ├── SKILL.md │ │ └── references/ │ │ ├── concurrency.md │ │ ├── generics.md │ │ ├── interfaces.md │ │ ├── project-structure.md │ │ └── testing.md │ └── skill-creator/ │ ├── LICENSE.txt │ ├── SKILL.md │ ├── agents/ │ │ ├── analyzer.md │ │ ├── comparator.md │ │ └── grader.md │ ├── assets/ │ │ └── eval_review.html │ ├── eval-viewer/ │ │ ├── generate_review.py │ │ └── viewer.html │ ├── references/ │ │ └── schemas.md │ └── scripts/ │ ├── aggregate_benchmark.py │ ├── generate_report.py │ ├── improve_description.py │ ├── package_skill.py │ ├── quick_validate.py │ ├── run_eval.py │ ├── run_loop.py │ └── utils.py ├── .gitignore ├── CLAUDE.md ├── LICENSE ├── README-EN.md ├── README.md ├── cmd/ │ └── server/ │ └── main.go ├── config.yml ├── docs/ │ ├── docs.go │ ├── swagger.json │ └── swagger.yaml ├── go.mod ├── go.sum ├── internal/ │ ├── api/ │ │ ├── handler/ │ │ │ ├── backup_handler.go │ │ │ ├── dst_api_handler.go │ │ │ ├── dst_config_handler.go │ │ │ ├── dst_map_handler.go │ │ │ ├── game_config_handler.go │ │ │ ├── game_handler.go │ │ │ ├── kv_handler.go │ │ │ ├── level_handler.go │ │ │ ├── level_log_handler.go │ │ │ ├── login_handler.go │ │ │ ├── mod_handler.go │ │ │ ├── player_handler.go │ │ │ ├── player_log_handler.go │ │ │ ├── statistics_handler.go │ │ │ └── update.go │ │ └── router.go │ ├── collect/ │ │ ├── collect.go │ │ └── collect_map.go │ ├── config/ │ │ └── config.go │ ├── database/ │ │ └── sqlite.go │ ├── middleware/ │ │ ├── auth.go │ │ ├── cluster.go │ │ ├── error.go │ │ └── start_before.go │ ├── model/ │ │ ├── LogRecord.go │ │ ├── announce.go │ │ ├── autoCheck.go │ │ ├── backup.go │ │ ├── backupSnapshot.go │ │ ├── cluster.go │ │ ├── connect.go │ │ ├── jobTask.go │ │ ├── kv.go │ │ ├── modInfo.go │ │ ├── modKv.go │ │ ├── model.go │ │ ├── playerLog.go │ │ ├── regenerate.go │ │ ├── spawnRole.go │ │ └── webLink.go │ ├── pkg/ │ │ ├── context/ │ │ │ └── cluster.go │ │ ├── response/ │ │ │ └── response.go │ │ └── utils/ │ │ ├── collectionUtils/ │ │ │ └── collectionUtils.go │ │ ├── dateUtils.go │ │ ├── dstUtils/ │ │ │ └── dstUtils.go │ │ ├── envUtils.go │ │ ├── fileUtils/ │ │ │ └── fileUtls.go │ │ ├── luaUtils/ │ │ │ └── luaUtils.go │ │ ├── shellUtils/ │ │ │ └── shellUitls.go │ │ ├── systemUtils/ │ │ │ └── SystemUtils.go │ │ └── zip/ │ │ └── zip.go │ └── service/ │ ├── archive/ │ │ └── path_resolver.go │ ├── backup/ │ │ └── backup_service.go │ ├── dstConfig/ │ │ ├── dst_config.go │ │ ├── factory.go │ │ └── one_dst_config.go │ ├── dstMap/ │ │ └── dst_map.go │ ├── dstPath/ │ │ ├── dst_path.go │ │ ├── linux_dst.go │ │ └── window_dst.go │ ├── game/ │ │ ├── factory.go │ │ ├── linux_process.go │ │ ├── process.go │ │ ├── windowGameCli.go │ │ └── window_process.go │ ├── gameArchive/ │ │ └── game_archive.go │ ├── gameConfig/ │ │ └── game_config.go │ ├── level/ │ │ └── level.go │ ├── levelConfig/ │ │ └── level_config.go │ ├── login/ │ │ └── login_service.go │ ├── mod/ │ │ └── mod_service.go │ ├── player/ │ │ └── player_service.go │ └── update/ │ ├── factory.go │ ├── linux_update.go │ ├── update.go │ └── window_update.go ├── scripts/ │ ├── build_linux.sh │ ├── build_swagger.sh │ ├── build_window.sh │ ├── docker/ │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── docker-entrypoint.sh │ │ ├── docker_build.sh │ │ └── docker_dst_config │ ├── docker-build-mac/ │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── docker-entrypoint.sh │ │ ├── docker_dst_config │ │ └── dst-mac-arm64-env-install.md │ └── py-dst-cli/ │ ├── README.md │ ├── dst_version.py │ ├── dst_world_setting.json │ ├── main.py │ ├── parse_TooManyItemPlus_items.py │ ├── parse_mod.py │ ├── parse_world_setting.py │ ├── parse_world_webp.py │ ├── requirements.txt │ └── steamapikey.txt └── static/ ├── Caves/ │ ├── leveldataoverride.lua │ ├── modoverrides.lua │ └── server.ini ├── Master/ │ ├── leveldataoverride.lua │ ├── modoverrides.lua │ └── server.ini ├── customcommands.lua └── template/ ├── caves_server.ini ├── cluster.ini ├── cluster2.ini ├── master_server.ini ├── server.ini └── test.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .claude/skills/api-generator/SKILL.md ================================================ --- name: api-generator description: Specialized skill for developing and refactoring the DST (Don't Starve Together) Admin Go project. Use this skill whenever the user mentions DST, game server management, API refactoring, adding handlers/services, creating CRUD endpoints, or working within the dst-admin-go codebase. This skill ensures all code follows the project's architectural patterns including dependency injection, layered architecture (Handler → Service → Model), and specific naming conventions. Make sure to use this skill when the user asks to refactor existing APIs, add new features, fix bugs, or modify any part of the dst-admin-go project structure. license: MIT metadata: author: DST Admin Go Team version: "2.0.0" domain: application triggers: DST, dst-admin-go, Don't Starve Together, game server, refactor API, add handler, create service, GORM, Gin, cluster management, backup service, player management, mod management, CRUD generator, generate API, create endpoint, 生成API, 创建接口 role: specialist scope: implementation output-format: code related-skills: golang-pro, golang-patterns --- # DST Admin Go API Generator Specialized skill for developing and refactoring the DST (Don't Starve Together) Admin Go project. Use this skill whenever the user mentions DST, game server management, API refactoring, adding handlers/services, creating CRUD endpoints, or working within the dst-admin-go codebase. This skill ensures all code follows the project's architectural patterns including dependency injection, layered architecture (Handler → Service → Model), and specific naming conventions. --- ## Project Context DST Admin Go is a web-based management panel for "Don't Starve Together" game servers written in Go. It follows a three-layer architecture: 1. **Handler Layer** (`internal/api/handler/`): HTTP request handling, validation, response formatting 2. **Service Layer** (`internal/service/`): Business logic, orchestration 3. **Model Layer** (`internal/model/`): Database entities (GORM) ### Architecture Patterns - **Dependency Injection**: All services instantiated in `internal/api/router.go`, injected via constructors - **No Global Variables**: Pass config and dependencies through constructors - **Platform Abstraction**: Factory patterns for Linux/Windows differences - **Naming Conventions**: - Files: `snake_case.go` (e.g., `backup_service.go`) - Structs: `PascalCase` without suffix (e.g., `BackupInfo`, NOT `BackupInfoVO`) - Constructors: `New{Name}` (e.g., `NewBackupService`) - Interfaces: Simple names (e.g., `Config`, `Process`) ### Project Structure ``` dst-admin-go/ ├── cmd/server/main.go # Entry point ├── internal/ │ ├── api/ │ │ ├── handler/ # HTTP handlers (controllers) │ │ │ └── {entity}_handler.go │ │ └── router.go # Route registration & DI │ ├── model/ # GORM models │ │ └── {entity}.go │ ├── service/ # Business logic │ │ └── {domain}/ │ │ ├── {domain}_service.go │ │ ├── factory.go # (if platform-specific) │ │ ├── linux_{domain}.go │ │ └── window_{domain}.go │ └── pkg/ │ ├── response/ # Standard responses │ └── utils/ # Utilities └── config.yml # Application config ``` --- ## Your Instructions You are an expert Go developer specializing in the DST Admin Go project. When the user requests creating a CRUD module, refactoring APIs, or adding new functionality: ### Step 1: Gather Requirements Ask the user for the following information (use a friendly, concise tone): 1. **Entity/Model Name**: What is the entity called? (e.g., "Announcement", "ModConfig", "Player") 2. **Chinese Name**: What is the Chinese name for Swagger docs? (e.g., "公告", "模组配置") 3. **Database Fields**: What fields does this entity have? - Field name, type (string, int, bool, time.Time, etc.) - GORM constraints (e.g., `unique`, `not null`, `default`) - JSON tag name (camelCase for API responses) - Example: `Title string, required, JSON: "title"` or `IsActive bool, default true, JSON: "isActive"` 4. **Operations Needed**: Which operations should be available? - Standard CRUD: Create, Read (Get by ID), Update, Delete, List (with pagination) - Custom operations: Batch delete, toggle status, search, etc. 5. **Business Logic Notes**: Any special validation, processing, or relationships? - E.g., "Must validate expiresAt is in the future", "Needs to interact with game process" 6. **Cluster Context**: Does this entity belong to a specific cluster/server? - If yes: Endpoints will be under `/api/{clusterName}/{entity}` and need cluster middleware ### Step 2: Analyze Dependencies Based on the requirements, determine: - **Always needed**: `*gorm.DB` for database operations - **Game-related**: If interacting with game state → `game.Process` - **File operations**: If handling files/archives → `archive.PathResolver` - **DST config**: If reading/writing DST configs → `dstConfig.Config` - **Level config**: If working with world configs → `levelConfig.LevelConfigUtils` - **Platform-specific**: If operations differ on Linux vs Windows → factory pattern ### Step 3: Generate Model File Create `internal/model/{entity}.go`: ```go package model import ( "gorm.io/gorm" "time" ) // {EntityName} {中文描述} type {EntityName} struct { gorm.Model // Fields based on user input Title string `json:"title" gorm:"type:varchar(255);not null"` Content string `json:"content" gorm:"type:text"` IsActive bool `json:"isActive" gorm:"default:true"` ExpiresAt *time.Time `json:"expiresAt"` } ``` **Guidelines**: - Always embed `gorm.Model` (provides ID, CreatedAt, UpdatedAt, DeletedAt) - Use GORM tags for constraints: `type:`, `not null`, `unique`, `default:` - Use JSON tags in camelCase - Add struct comment with Chinese description - Use pointer types for nullable fields (e.g., `*time.Time`, `*string`) ### Step 4: Generate Service File Create `internal/service/{domain}/{domain}_service.go`: ```go package {domain} import ( "dst-admin-go/internal/model" "gorm.io/gorm" ) type {Entity}Service struct { db *gorm.DB // Add other dependencies as detected } func New{Entity}Service(db *gorm.DB /* other deps */) *{Entity}Service { return &{Entity}Service{ db: db, } } // List{Entity} 获取{中文名}列表 func (s *{Entity}Service) List{Entity}(page, pageSize int) ([]model.{Entity}, int64, error) { var list []model.{Entity} var total int64 offset := (page - 1) * pageSize err := s.db.Model(&model.{Entity}{}).Count(&total).Error if err != nil { return nil, 0, err } err = s.db.Offset(offset).Limit(pageSize).Find(&list).Error return list, total, err } // Get{Entity} 获取{中文名}详情 func (s *{Entity}Service) Get{Entity}(id uint) (*model.{Entity}, error) { var entity model.{Entity} err := s.db.First(&entity, id).Error return &entity, err } // Create{Entity} 创建{中文名} func (s *{Entity}Service) Create{Entity}(entity *model.{Entity}) error { return s.db.Create(entity).Error } // Update{Entity} 更新{中文名} func (s *{Entity}Service) Update{Entity}(entity *model.{Entity}) error { return s.db.Save(entity).Error } // Delete{Entity} 删除{中文名} func (s *{Entity}Service) Delete{Entity}(id uint) error { return s.db.Delete(&model.{Entity}{}, id).Error } ``` **Guidelines**: - Constructor accepts all dependencies - Chinese comments for all exported methods - Use GORM for database operations - Add pagination support for List (offset/limit) - Return errors, don't handle them here - Add custom business logic methods as needed ### Step 5: Generate Handler File Create `internal/api/handler/{entity}_handler.go`: ```go package handler import ( "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/{domain}" "github.com/gin-gonic/gin" "net/http" "strconv" ) type {Entity}Handler struct { service *{domain}.{Entity}Service } func New{Entity}Handler(service *{domain}.{Entity}Service) *{Entity}Handler { return &{Entity}Handler{service: service} } func (h *{Entity}Handler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/{entity}/list", h.List) router.GET("/api/{entity}/:id", h.Get) router.POST("/api/{entity}", h.Create) router.PUT("/api/{entity}/:id", h.Update) router.DELETE("/api/{entity}/:id", h.Delete) } // List 获取{中文名}列表 // @Summary 获取{中文名}列表 // @Description 分页获取{中文名}列表 // @Tags {entity} // @Accept json // @Produce json // @Param page query int false "页码" default(1) // @Param pageSize query int false "每页数量" default(10) // @Success 200 {object} response.Response{data=object{list=[]model.{Entity},total=int,page=int,pageSize=int}} // @Router /api/{entity}/list [get] func (h *{Entity}Handler) List(ctx *gin.Context) { page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1")) pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10")) if page < 1 { page = 1 } if pageSize < 1 || pageSize > 100 { pageSize = 10 } list, total, err := h.service.List{Entity}(page, pageSize) if err != nil { response.FailWithMessage("获取列表失败: "+err.Error(), ctx) return } response.OkWithData(gin.H{ "list": list, "total": total, "page": page, "pageSize": pageSize, }, ctx) } // Get 获取{中文名}详情 // @Summary 获取{中文名}详情 // @Description 根据ID获取{中文名}详情 // @Tags {entity} // @Accept json // @Produce json // @Param id path int true "{中文名}ID" // @Success 200 {object} response.Response{data=model.{Entity}} // @Router /api/{entity}/{id} [get] func (h *{Entity}Handler) Get(ctx *gin.Context) { id, err := strconv.ParseUint(ctx.Param("id"), 10, 32) if err != nil { response.FailWithMessage("无效的ID", ctx) return } entity, err := h.service.Get{Entity}(uint(id)) if err != nil { response.FailWithMessage("获取详情失败: "+err.Error(), ctx) return } response.OkWithData(entity, ctx) } // Create 创建{中文名} // @Summary 创建{中文名} // @Description 创建新的{中文名} // @Tags {entity} // @Accept json // @Produce json // @Param data body model.{Entity} true "{中文名}信息" // @Success 200 {object} response.Response{data=model.{Entity}} // @Router /api/{entity} [post] func (h *{Entity}Handler) Create(ctx *gin.Context) { var entity model.{Entity} if err := ctx.ShouldBindJSON(&entity); err != nil { response.FailWithMessage("参数错误: "+err.Error(), ctx) return } if err := h.service.Create{Entity}(&entity); err != nil { response.FailWithMessage("创建失败: "+err.Error(), ctx) return } response.OkWithData(entity, ctx) } // Update 更新{中文名} // @Summary 更新{中文名} // @Description 更新{中文名}信息 // @Tags {entity} // @Accept json // @Produce json // @Param id path int true "{中文名}ID" // @Param data body model.{Entity} true "{中文名}信息" // @Success 200 {object} response.Response{data=model.{Entity}} // @Router /api/{entity}/{id} [put] func (h *{Entity}Handler) Update(ctx *gin.Context) { id, err := strconv.ParseUint(ctx.Param("id"), 10, 32) if err != nil { response.FailWithMessage("无效的ID", ctx) return } var entity model.{Entity} if err := ctx.ShouldBindJSON(&entity); err != nil { response.FailWithMessage("参数错误: "+err.Error(), ctx) return } entity.ID = uint(id) if err := h.service.Update{Entity}(&entity); err != nil { response.FailWithMessage("更新失败: "+err.Error(), ctx) return } response.OkWithData(entity, ctx) } // Delete 删除{中文名} // @Summary 删除{中文名} // @Description 根据ID删除{中文名} // @Tags {entity} // @Accept json // @Produce json // @Param id path int true "{中文名}ID" // @Success 200 {object} response.Response // @Router /api/{entity}/{id} [delete] func (h *{Entity}Handler) Delete(ctx *gin.Context) { id, err := strconv.ParseUint(ctx.Param("id"), 10, 32) if err != nil { response.FailWithMessage("无效的ID", ctx) return } if err := h.service.Delete{Entity}(uint(id)); err != nil { response.FailWithMessage("删除失败: "+err.Error(), ctx) return } response.OkWithMessage("删除成功", ctx) } ``` **Guidelines**: - Complete Swagger annotations for every handler - Use `response.Response` helpers: `OkWithData`, `FailWithMessage`, `OkWithMessage` - Validate all input parameters - Chinese error messages - Parse ID from path parameter as uint - Bind JSON request body with `ShouldBindJSON` - Return HTTP 200 even for errors (error code in response body) ### Step 6: Update Router Read `internal/api/router.go` and make these changes: 1. **Add import** (if not exists): ```go "{domain}" "dst-admin-go/internal/service/{domain}" ``` 2. **In `Register()` function, add service initialization** (after existing services): ```go // {entity} service {entity}Service := {domain}.New{Entity}Service(db /* add detected dependencies */) ``` 3. **Add handler initialization** (after existing handlers): ```go {entity}Handler := handler.New{Entity}Handler({entity}Service) ``` 4. **Add route registration** (after existing routes): ```go {entity}Handler.RegisterRoute(router) ``` **Important**: Maintain the existing order and formatting. Add new code at the end of each section. ### Step 7: Handle Platform-Specific Code (if needed) If the service needs platform-specific behavior: 1. Create `internal/service/{domain}/factory.go`: ```go package {domain} import ( "gorm.io/gorm" "runtime" ) func New{Entity}Service(db *gorm.DB) {Entity}Service { if runtime.GOOS == "windows" { return &Windows{Entity}Service{db: db} } return &Linux{Entity}Service{db: db} } ``` 2. Create interface in `{domain}_service.go`: ```go type {Entity}Service interface { List{Entity}(page, pageSize int) ([]model.{Entity}, int64, error) // ... other methods } ``` 3. Create platform implementations: - `internal/service/{domain}/linux_{domain}.go` - `internal/service/{domain}/window_{domain}.go` ### Step 8: Verify and Test After generating all files: 1. **Run compilation check**: ```bash go mod tidy go build cmd/server/main.go ``` 2. **Report to user**: - List all generated files - Show modified files (router.go) - Provide curl test commands - Mention Swagger UI location 3. **Provide test commands**: ```bash # List curl -X GET "http://localhost:8082/api/{entity}/list?page=1&pageSize=10" # Create curl -X POST "http://localhost:8082/api/{entity}" \ -H "Content-Type: application/json" \ -d '{"field1": "value1", "field2": "value2"}' # Get curl -X GET "http://localhost:8082/api/{entity}/1" # Update curl -X PUT "http://localhost:8082/api/{entity}/1" \ -H "Content-Type: application/json" \ -d '{"field1": "new_value"}' # Delete curl -X DELETE "http://localhost:8082/api/{entity}/1" ``` 4. **Remind user**: Access Swagger UI at `http://localhost:8082/swagger/index.html` (after running the server) --- ## Common Patterns Reference ### Response Helpers Located in `internal/pkg/response/response.go`: ```go // Success with data response.OkWithData(data, ctx) // Success with message response.OkWithMessage("操作成功", ctx) // Error with message response.FailWithMessage("操作失败: "+err.Error(), ctx) ``` ### Common Dependencies - `*gorm.DB`: Database access - `*gin.Context`: HTTP request context - `dstConfig.Config`: DST configuration interface - `game.Process`: Game process management interface - `archive.PathResolver`: Archive path resolution - `levelConfig.LevelConfigUtils`: Level config parsing ### Cluster-Aware Endpoints If entity belongs to a cluster, routes should be: ```go router.GET("/api/:cluster_name/{entity}/list", h.List) router.GET("/api/:cluster_name/{entity}/:id", h.Get) // etc. ``` **IMPORTANT**: Handler should use cluster context helper to get clusterName: ```go import "dst-admin-go/internal/pkg/context" clusterName := context.GetClusterName(ctx) // Use clusterName in service calls ``` **DO NOT** use `ctx.Query("clusterName")` or `ctx.Param("cluster_name")` directly. Always use `context.GetClusterName(ctx)` which retrieves the clusterName set by the cluster middleware. ### Pagination Pattern Always use this pattern for list endpoints: ```go page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1")) pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10")) if page < 1 { page = 1 } if pageSize < 1 || pageSize > 100 { pageSize = 10 } offset := (page - 1) * pageSize ``` ### GORM Common Tags - `type:varchar(255)` - String with length - `type:text` - Long text - `not null` - Required field - `unique` - Unique constraint - `default:true` - Default value - `index` - Create index - `foreignKey:UserID` - Foreign key --- ## Examples ### Example 1: Simple Announcement System **User Input**: - Entity: Announcement - Chinese: 公告 - Fields: Title (string, required), Content (text), IsActive (bool, default true), ExpiresAt (time, nullable) - Operations: Full CRUD + List - Cluster context: No **Generated Files**: - `internal/model/announce.go` - `internal/service/announce/announce_service.go` - `internal/api/handler/announce_handler.go` - Modified: `internal/api/router.go` ### Example 2: Mod Management (Game-Related) **User Input**: - Entity: ModInfo - Chinese: 模组信息 - Fields: ModId (string, unique), Name (string), Author (string), Version (string), IsEnabled (bool), ClusterName (string) - Operations: Full CRUD + List + Toggle status - Business logic: Needs to interact with game process when toggling - Cluster context: Yes **Generated Files**: - `internal/model/modInfo.go` - `internal/service/mod/mod_service.go` (with `game.Process` dependency) - `internal/api/handler/mod_handler.go` (with cluster-aware routes) - Modified: `internal/api/router.go` **Additional method in service**: ```go // ToggleModStatus 切换模组启用状态 func (s *ModService) ToggleModStatus(clusterName, modId string) error { // Update database // Interact with game process return nil } ``` --- ## Critical Checklist Before completing the task, verify: - [ ] Model file has `gorm.Model` embedded - [ ] All fields have both `json` and `gorm` tags - [ ] Service has constructor accepting all dependencies - [ ] All service methods have Chinese comments - [ ] Handler has `RegisterRoute` method - [ ] All handler methods have complete Swagger annotations - [ ] Swagger tags use entity name (e.g., `@Tags announcement`) - [ ] Chinese names used in Swagger summaries - [ ] router.go has import added - [ ] router.go has service initialization - [ ] router.go has handler initialization - [ ] router.go has route registration - [ ] Naming follows conventions (snake_case files, PascalCase types, no VO suffix) - [ ] Code compiles without errors - [ ] Test commands provided to user --- ## DST-Specific Domain Knowledge ### Cluster Architecture A **cluster** contains multiple **levels** (worlds): - **Master** - Overworld (surface world) - **Caves** - Underground world Each level runs as a separate process with its own configuration. ### Important Paths ```go // Use pathResolver service for all path operations pathResolver.ClusterPath(clusterName) // e.g., ~/.klei/DoNotStarveTogether/MyCluster/ pathResolver.LevelPath(clusterName, "Master") // e.g., ~/.klei/DoNotStarveTogether/MyCluster/Master/ pathResolver.SavePath(clusterName, "Master") // e.g., ~/.klei/DoNotStarveTogether/MyCluster/Master/save/ ``` ### Configuration Files - `cluster.ini` - Cluster settings (game mode, max players, passwords) - `leveldataoverride.lua` - World generation settings (Lua table format) - `modoverrides.lua` - Enabled mods configuration (Lua table format) - `server.ini` - Server-specific settings Use `luaUtils` package to parse/generate Lua configuration files. ### Process Management **Linux**: Uses `screen` sessions ```go screenName := fmt.Sprintf("dst_%s_%s", clusterName, levelName) ``` **Windows**: Uses custom CLI wrapper (`windowGameCli.go`) --- ## Common Utilities ### File Operations ```go import "dst-admin-go/internal/pkg/utils/fileUtils" fileUtils.PathExists(path) fileUtils.CreateDir(path) fileUtils.CopyFile(src, dst) fileUtils.Unzip(zipPath, destPath) ``` ### Shell Commands ```go import "dst-admin-go/internal/pkg/utils/shellUtils" output, err := shellUtils.ExecuteCommand("ls", "-la") ``` ### Lua Configuration ```go import "dst-admin-go/internal/pkg/utils/luaUtils" // Parse Lua table to map config, err := luaUtils.ParseLuaTable(luaContent) // Generate Lua table from map luaContent := luaUtils.GenerateLuaTable(configMap) ``` --- ## Tips - **Be concise**: Don't over-explain. Generate code efficiently. - **Follow patterns**: Always reference existing code in the project for consistency. - **Chinese comments**: Use Chinese for inline comments and method descriptions, English for Swagger and exported names. - **Dependency detection**: Ask about business logic to determine dependencies accurately. - **Platform awareness**: Ask if operations differ on Windows vs Linux. - **Cluster context**: Ask if entity belongs to a specific cluster/server. - **Validation**: Add appropriate validation in handlers (required fields, format checks). - **Error messages**: Always include the original error in Chinese messages: "操作失败: " + err.Error() --- ## When NOT to Use This Skill Don't use this skill if: - User is asking general Go questions (not specific to DST Admin Go) - User wants to modify frontend code - User is asking about Docker, deployment, or infrastructure - Task doesn't involve creating/modifying handlers, services, or models In those cases, handle the request normally without the skill context. --- ## Summary This skill automates the creation of complete CRUD modules in DST Admin Go following the project's three-layer architecture. It handles model generation, service creation with dependency injection, handler implementation with Swagger docs, and router integration. Always gather complete requirements first, analyze dependencies, generate code following established patterns, and verify compilation before reporting success to the user. ================================================ FILE: .claude/skills/find-skills/SKILL.md ================================================ --- name: find-skills description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill. --- # Find Skills This skill helps you discover and install skills from the open agent skills ecosystem. ## When to Use This Skill Use this skill when the user: - Asks "how do I do X" where X might be a common task with an existing skill - Says "find a skill for X" or "is there a skill for X" - Asks "can you do X" where X is a specialized capability - Expresses interest in extending agent capabilities - Wants to search for tools, templates, or workflows - Mentions they wish they had help with a specific domain (design, testing, deployment, etc.) ## What is the Skills CLI? The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools. **Key commands:** - `npx skills find [query]` - Search for skills interactively or by keyword - `npx skills add ` - Install a skill from GitHub or other sources - `npx skills check` - Check for skill updates - `npx skills update` - Update all installed skills **Browse skills at:** https://skills.sh/ ## How to Help Users Find Skills ### Step 1: Understand What They Need When a user asks for help with something, identify: 1. The domain (e.g., React, testing, design, deployment) 2. The specific task (e.g., writing tests, creating animations, reviewing PRs) 3. Whether this is a common enough task that a skill likely exists ### Step 2: Search for Skills Run the find command with a relevant query: ```bash npx skills find [query] ``` For example: - User asks "how do I make my React app faster?" → `npx skills find react performance` - User asks "can you help me with PR reviews?" → `npx skills find pr review` - User asks "I need to create a changelog" → `npx skills find changelog` The command will return results like: ``` Install with npx skills add vercel-labs/agent-skills@vercel-react-best-practices └ https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices ``` ### Step 3: Present Options to the User When you find relevant skills, present them to the user with: 1. The skill name and what it does 2. The install command they can run 3. A link to learn more at skills.sh Example response: ``` I found a skill that might help! The "vercel-react-best-practices" skill provides React and Next.js performance optimization guidelines from Vercel Engineering. To install it: npx skills add vercel-labs/agent-skills@vercel-react-best-practices Learn more: https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices ``` ### Step 4: Offer to Install If the user wants to proceed, you can install the skill for them: ```bash npx skills add -g -y ``` The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts. ## Common Skill Categories When searching, consider these common categories: | Category | Example Queries | | --------------- | ---------------------------------------- | | Web Development | react, nextjs, typescript, css, tailwind | | Testing | testing, jest, playwright, e2e | | DevOps | deploy, docker, kubernetes, ci-cd | | Documentation | docs, readme, changelog, api-docs | | Code Quality | review, lint, refactor, best-practices | | Design | ui, ux, design-system, accessibility | | Productivity | workflow, automation, git | ## Tips for Effective Searches 1. **Use specific keywords**: "react testing" is better than just "testing" 2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd" 3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills` ## When No Skills Are Found If no relevant skills exist: 1. Acknowledge that no existing skill was found 2. Offer to help with the task directly using your general capabilities 3. Suggest the user could create their own skill with `npx skills init` Example: ``` I searched for skills related to "xyz" but didn't find any matches. I can still help you with this task directly! Would you like me to proceed? If this is something you do often, you could create your own skill: npx skills init my-xyz-skill ``` ================================================ FILE: .claude/skills/go-concurrency-patterns/SKILL.md ================================================ --- name: go-concurrency-patterns description: Master Go concurrency with goroutines, channels, sync primitives, and context. Use when building concurrent Go applications, implementing worker pools, or debugging race conditions. --- # Go Concurrency Patterns Production patterns for Go concurrency including goroutines, channels, synchronization primitives, and context management. ## When to Use This Skill - Building concurrent Go applications - Implementing worker pools and pipelines - Managing goroutine lifecycles - Using channels for communication - Debugging race conditions - Implementing graceful shutdown ## Core Concepts ### 1. Go Concurrency Primitives | Primitive | Purpose | | ----------------- | -------------------------------- | | `goroutine` | Lightweight concurrent execution | | `channel` | Communication between goroutines | | `select` | Multiplex channel operations | | `sync.Mutex` | Mutual exclusion | | `sync.WaitGroup` | Wait for goroutines to complete | | `context.Context` | Cancellation and deadlines | ### 2. Go Concurrency Mantra ``` Don't communicate by sharing memory; share memory by communicating. ``` ## Quick Start ```go package main import ( "context" "fmt" "sync" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() results := make(chan string, 10) var wg sync.WaitGroup // Spawn workers for i := 0; i < 3; i++ { wg.Add(1) go worker(ctx, i, results, &wg) } // Close results when done go func() { wg.Wait() close(results) }() // Collect results for result := range results { fmt.Println(result) } } func worker(ctx context.Context, id int, results chan<- string, wg *sync.WaitGroup) { defer wg.Done() select { case <-ctx.Done(): return case results <- fmt.Sprintf("Worker %d done", id): } } ``` ## Patterns ### Pattern 1: Worker Pool ```go package main import ( "context" "fmt" "sync" ) type Job struct { ID int Data string } type Result struct { JobID int Output string Err error } func WorkerPool(ctx context.Context, numWorkers int, jobs <-chan Job) <-chan Result { results := make(chan Result, len(jobs)) var wg sync.WaitGroup for i := 0; i < numWorkers; i++ { wg.Add(1) go func(workerID int) { defer wg.Done() for job := range jobs { select { case <-ctx.Done(): return default: result := processJob(job) results <- result } } }(i) } go func() { wg.Wait() close(results) }() return results } func processJob(job Job) Result { // Simulate work return Result{ JobID: job.ID, Output: fmt.Sprintf("Processed: %s", job.Data), } } // Usage func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() jobs := make(chan Job, 100) // Send jobs go func() { for i := 0; i < 50; i++ { jobs <- Job{ID: i, Data: fmt.Sprintf("job-%d", i)} } close(jobs) }() // Process with 5 workers results := WorkerPool(ctx, 5, jobs) for result := range results { fmt.Printf("Result: %+v\n", result) } } ``` ### Pattern 2: Fan-Out/Fan-In Pipeline ```go package main import ( "context" "sync" ) // Stage 1: Generate numbers func generate(ctx context.Context, nums ...int) <-chan int { out := make(chan int) go func() { defer close(out) for _, n := range nums { select { case <-ctx.Done(): return case out <- n: } } }() return out } // Stage 2: Square numbers (can run multiple instances) func square(ctx context.Context, in <-chan int) <-chan int { out := make(chan int) go func() { defer close(out) for n := range in { select { case <-ctx.Done(): return case out <- n * n: } } }() return out } // Fan-in: Merge multiple channels into one func merge(ctx context.Context, cs ...<-chan int) <-chan int { var wg sync.WaitGroup out := make(chan int) // Start output goroutine for each input channel output := func(c <-chan int) { defer wg.Done() for n := range c { select { case <-ctx.Done(): return case out <- n: } } } wg.Add(len(cs)) for _, c := range cs { go output(c) } // Close out after all inputs are done go func() { wg.Wait() close(out) }() return out } func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Generate input in := generate(ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // Fan out to multiple squarers c1 := square(ctx, in) c2 := square(ctx, in) c3 := square(ctx, in) // Fan in results for result := range merge(ctx, c1, c2, c3) { fmt.Println(result) } } ``` ### Pattern 3: Bounded Concurrency with Semaphore ```go package main import ( "context" "fmt" "golang.org/x/sync/semaphore" "sync" ) type RateLimitedWorker struct { sem *semaphore.Weighted } func NewRateLimitedWorker(maxConcurrent int64) *RateLimitedWorker { return &RateLimitedWorker{ sem: semaphore.NewWeighted(maxConcurrent), } } func (w *RateLimitedWorker) Do(ctx context.Context, tasks []func() error) []error { var ( wg sync.WaitGroup mu sync.Mutex errors []error ) for _, task := range tasks { // Acquire semaphore (blocks if at limit) if err := w.sem.Acquire(ctx, 1); err != nil { return []error{err} } wg.Add(1) go func(t func() error) { defer wg.Done() defer w.sem.Release(1) if err := t(); err != nil { mu.Lock() errors = append(errors, err) mu.Unlock() } }(task) } wg.Wait() return errors } // Alternative: Channel-based semaphore type Semaphore chan struct{} func NewSemaphore(n int) Semaphore { return make(chan struct{}, n) } func (s Semaphore) Acquire() { s <- struct{}{} } func (s Semaphore) Release() { <-s } ``` ### Pattern 4: Graceful Shutdown ```go package main import ( "context" "fmt" "os" "os/signal" "sync" "syscall" "time" ) type Server struct { shutdown chan struct{} wg sync.WaitGroup } func NewServer() *Server { return &Server{ shutdown: make(chan struct{}), } } func (s *Server) Start(ctx context.Context) { // Start workers for i := 0; i < 5; i++ { s.wg.Add(1) go s.worker(ctx, i) } } func (s *Server) worker(ctx context.Context, id int) { defer s.wg.Done() defer fmt.Printf("Worker %d stopped\n", id) ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): // Cleanup fmt.Printf("Worker %d cleaning up...\n", id) time.Sleep(500 * time.Millisecond) // Simulated cleanup return case <-ticker.C: fmt.Printf("Worker %d working...\n", id) } } } func (s *Server) Shutdown(timeout time.Duration) { // Signal shutdown close(s.shutdown) // Wait with timeout done := make(chan struct{}) go func() { s.wg.Wait() close(done) }() select { case <-done: fmt.Println("Clean shutdown completed") case <-time.After(timeout): fmt.Println("Shutdown timed out, forcing exit") } } func main() { // Setup signal handling ctx, cancel := context.WithCancel(context.Background()) sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) server := NewServer() server.Start(ctx) // Wait for signal sig := <-sigCh fmt.Printf("\nReceived signal: %v\n", sig) // Cancel context to stop workers cancel() // Wait for graceful shutdown server.Shutdown(5 * time.Second) } ``` ### Pattern 5: Error Group with Cancellation ```go package main import ( "context" "fmt" "golang.org/x/sync/errgroup" "net/http" ) func fetchAllURLs(ctx context.Context, urls []string) ([]string, error) { g, ctx := errgroup.WithContext(ctx) results := make([]string, len(urls)) for i, url := range urls { i, url := i, url // Capture loop variables g.Go(func() error { req, err := http.NewRequestWithContext(ctx, "GET", url, nil) if err != nil { return fmt.Errorf("creating request for %s: %w", url, err) } resp, err := http.DefaultClient.Do(req) if err != nil { return fmt.Errorf("fetching %s: %w", url, err) } defer resp.Body.Close() results[i] = fmt.Sprintf("%s: %d", url, resp.StatusCode) return nil }) } // Wait for all goroutines to complete or one to fail if err := g.Wait(); err != nil { return nil, err // First error cancels all others } return results, nil } // With concurrency limit func fetchWithLimit(ctx context.Context, urls []string, limit int) ([]string, error) { g, ctx := errgroup.WithContext(ctx) g.SetLimit(limit) // Max concurrent goroutines results := make([]string, len(urls)) var mu sync.Mutex for i, url := range urls { i, url := i, url g.Go(func() error { result, err := fetchURL(ctx, url) if err != nil { return err } mu.Lock() results[i] = result mu.Unlock() return nil }) } if err := g.Wait(); err != nil { return nil, err } return results, nil } ``` ### Pattern 6: Concurrent Map with sync.Map ```go package main import ( "sync" ) // For frequent reads, infrequent writes type Cache struct { m sync.Map } func (c *Cache) Get(key string) (interface{}, bool) { return c.m.Load(key) } func (c *Cache) Set(key string, value interface{}) { c.m.Store(key, value) } func (c *Cache) GetOrSet(key string, value interface{}) (interface{}, bool) { return c.m.LoadOrStore(key, value) } func (c *Cache) Delete(key string) { c.m.Delete(key) } // For write-heavy workloads, use sharded map type ShardedMap struct { shards []*shard numShards int } type shard struct { sync.RWMutex data map[string]interface{} } func NewShardedMap(numShards int) *ShardedMap { m := &ShardedMap{ shards: make([]*shard, numShards), numShards: numShards, } for i := range m.shards { m.shards[i] = &shard{data: make(map[string]interface{})} } return m } func (m *ShardedMap) getShard(key string) *shard { // Simple hash h := 0 for _, c := range key { h = 31*h + int(c) } return m.shards[h%m.numShards] } func (m *ShardedMap) Get(key string) (interface{}, bool) { shard := m.getShard(key) shard.RLock() defer shard.RUnlock() v, ok := shard.data[key] return v, ok } func (m *ShardedMap) Set(key string, value interface{}) { shard := m.getShard(key) shard.Lock() defer shard.Unlock() shard.data[key] = value } ``` ### Pattern 7: Select with Timeout and Default ```go func selectPatterns() { ch := make(chan int) // Timeout pattern select { case v := <-ch: fmt.Println("Received:", v) case <-time.After(time.Second): fmt.Println("Timeout!") } // Non-blocking send/receive select { case ch <- 42: fmt.Println("Sent") default: fmt.Println("Channel full, skipping") } // Priority select (check high priority first) highPriority := make(chan int) lowPriority := make(chan int) for { select { case msg := <-highPriority: fmt.Println("High priority:", msg) default: select { case msg := <-highPriority: fmt.Println("High priority:", msg) case msg := <-lowPriority: fmt.Println("Low priority:", msg) } } } } ``` ## Race Detection ```bash # Run tests with race detector go test -race ./... # Build with race detector go build -race . # Run with race detector go run -race main.go ``` ## Best Practices ### Do's - **Use context** - For cancellation and deadlines - **Close channels** - From sender side only - **Use errgroup** - For concurrent operations with errors - **Buffer channels** - When you know the count - **Prefer channels** - Over mutexes when possible ### Don'ts - **Don't leak goroutines** - Always have exit path - **Don't close from receiver** - Causes panic - **Don't use shared memory** - Unless necessary - **Don't ignore context cancellation** - Check ctx.Done() - **Don't use time.Sleep for sync** - Use proper primitives ## Resources - [Go Concurrency Patterns](https://go.dev/blog/pipelines) - [Effective Go - Concurrency](https://go.dev/doc/effective_go#concurrency) - [Go by Example - Goroutines](https://gobyexample.com/goroutines) ================================================ FILE: .claude/skills/golang-patterns/SKILL.md ================================================ --- name: golang-patterns description: Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable Go applications. origin: ECC --- # Go Development Patterns Idiomatic Go patterns and best practices for building robust, efficient, and maintainable applications. ## When to Activate - Writing new Go code - Reviewing Go code - Refactoring existing Go code - Designing Go packages/modules ## Core Principles ### 1. Simplicity and Clarity Go favors simplicity over cleverness. Code should be obvious and easy to read. ```go // Good: Clear and direct func GetUser(id string) (*User, error) { user, err := db.FindUser(id) if err != nil { return nil, fmt.Errorf("get user %s: %w", id, err) } return user, nil } // Bad: Overly clever func GetUser(id string) (*User, error) { return func() (*User, error) { if u, e := db.FindUser(id); e == nil { return u, nil } else { return nil, e } }() } ``` ### 2. Make the Zero Value Useful Design types so their zero value is immediately usable without initialization. ```go // Good: Zero value is useful type Counter struct { mu sync.Mutex count int // zero value is 0, ready to use } func (c *Counter) Inc() { c.mu.Lock() c.count++ c.mu.Unlock() } // Good: bytes.Buffer works with zero value var buf bytes.Buffer buf.WriteString("hello") // Bad: Requires initialization type BadCounter struct { counts map[string]int // nil map will panic } ``` ### 3. Accept Interfaces, Return Structs Functions should accept interface parameters and return concrete types. ```go // Good: Accepts interface, returns concrete type func ProcessData(r io.Reader) (*Result, error) { data, err := io.ReadAll(r) if err != nil { return nil, err } return &Result{Data: data}, nil } // Bad: Returns interface (hides implementation details unnecessarily) func ProcessData(r io.Reader) (io.Reader, error) { // ... } ``` ## Error Handling Patterns ### Error Wrapping with Context ```go // Good: Wrap errors with context func LoadConfig(path string) (*Config, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("load config %s: %w", path, err) } var cfg Config if err := json.Unmarshal(data, &cfg); err != nil { return nil, fmt.Errorf("parse config %s: %w", path, err) } return &cfg, nil } ``` ### Custom Error Types ```go // Define domain-specific errors type ValidationError struct { Field string Message string } func (e *ValidationError) Error() string { return fmt.Sprintf("validation failed on %s: %s", e.Field, e.Message) } // Sentinel errors for common cases var ( ErrNotFound = errors.New("resource not found") ErrUnauthorized = errors.New("unauthorized") ErrInvalidInput = errors.New("invalid input") ) ``` ### Error Checking with errors.Is and errors.As ```go func HandleError(err error) { // Check for specific error if errors.Is(err, sql.ErrNoRows) { log.Println("No records found") return } // Check for error type var validationErr *ValidationError if errors.As(err, &validationErr) { log.Printf("Validation error on field %s: %s", validationErr.Field, validationErr.Message) return } // Unknown error log.Printf("Unexpected error: %v", err) } ``` ### Never Ignore Errors ```go // Bad: Ignoring error with blank identifier result, _ := doSomething() // Good: Handle or explicitly document why it's safe to ignore result, err := doSomething() if err != nil { return err } // Acceptable: When error truly doesn't matter (rare) _ = writer.Close() // Best-effort cleanup, error logged elsewhere ``` ## Concurrency Patterns ### Worker Pool ```go func WorkerPool(jobs <-chan Job, results chan<- Result, numWorkers int) { var wg sync.WaitGroup for i := 0; i < numWorkers; i++ { wg.Add(1) go func() { defer wg.Done() for job := range jobs { results <- process(job) } }() } wg.Wait() close(results) } ``` ### Context for Cancellation and Timeouts ```go func FetchWithTimeout(ctx context.Context, url string) ([]byte, error) { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", url, nil) if err != nil { return nil, fmt.Errorf("create request: %w", err) } resp, err := http.DefaultClient.Do(req) if err != nil { return nil, fmt.Errorf("fetch %s: %w", url, err) } defer resp.Body.Close() return io.ReadAll(resp.Body) } ``` ### Graceful Shutdown ```go func GracefulShutdown(server *http.Server) { quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("Shutting down server...") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := server.Shutdown(ctx); err != nil { log.Fatalf("Server forced to shutdown: %v", err) } log.Println("Server exited") } ``` ### errgroup for Coordinated Goroutines ```go import "golang.org/x/sync/errgroup" func FetchAll(ctx context.Context, urls []string) ([][]byte, error) { g, ctx := errgroup.WithContext(ctx) results := make([][]byte, len(urls)) for i, url := range urls { i, url := i, url // Capture loop variables g.Go(func() error { data, err := FetchWithTimeout(ctx, url) if err != nil { return err } results[i] = data return nil }) } if err := g.Wait(); err != nil { return nil, err } return results, nil } ``` ### Avoiding Goroutine Leaks ```go // Bad: Goroutine leak if context is cancelled func leakyFetch(ctx context.Context, url string) <-chan []byte { ch := make(chan []byte) go func() { data, _ := fetch(url) ch <- data // Blocks forever if no receiver }() return ch } // Good: Properly handles cancellation func safeFetch(ctx context.Context, url string) <-chan []byte { ch := make(chan []byte, 1) // Buffered channel go func() { data, err := fetch(url) if err != nil { return } select { case ch <- data: case <-ctx.Done(): } }() return ch } ``` ## Interface Design ### Small, Focused Interfaces ```go // Good: Single-method interfaces type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } type Closer interface { Close() error } // Compose interfaces as needed type ReadWriteCloser interface { Reader Writer Closer } ``` ### Define Interfaces Where They're Used ```go // In the consumer package, not the provider package service // UserStore defines what this service needs type UserStore interface { GetUser(id string) (*User, error) SaveUser(user *User) error } type Service struct { store UserStore } // Concrete implementation can be in another package // It doesn't need to know about this interface ``` ### Optional Behavior with Type Assertions ```go type Flusher interface { Flush() error } func WriteAndFlush(w io.Writer, data []byte) error { if _, err := w.Write(data); err != nil { return err } // Flush if supported if f, ok := w.(Flusher); ok { return f.Flush() } return nil } ``` ## Package Organization ### Standard Project Layout ```text myproject/ ├── cmd/ │ └── myapp/ │ └── main.go # Entry point ├── internal/ │ ├── handler/ # HTTP handlers │ ├── service/ # Business logic │ ├── repository/ # Data access │ └── config/ # Configuration ├── pkg/ │ └── client/ # Public API client ├── api/ │ └── v1/ # API definitions (proto, OpenAPI) ├── testdata/ # Test fixtures ├── go.mod ├── go.sum └── Makefile ``` ### Package Naming ```go // Good: Short, lowercase, no underscores package http package json package user // Bad: Verbose, mixed case, or redundant package httpHandler package json_parser package userService // Redundant 'Service' suffix ``` ### Avoid Package-Level State ```go // Bad: Global mutable state var db *sql.DB func init() { db, _ = sql.Open("postgres", os.Getenv("DATABASE_URL")) } // Good: Dependency injection type Server struct { db *sql.DB } func NewServer(db *sql.DB) *Server { return &Server{db: db} } ``` ## Struct Design ### Functional Options Pattern ```go type Server struct { addr string timeout time.Duration logger *log.Logger } type Option func(*Server) func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } } func WithLogger(l *log.Logger) Option { return func(s *Server) { s.logger = l } } func NewServer(addr string, opts ...Option) *Server { s := &Server{ addr: addr, timeout: 30 * time.Second, // default logger: log.Default(), // default } for _, opt := range opts { opt(s) } return s } // Usage server := NewServer(":8080", WithTimeout(60*time.Second), WithLogger(customLogger), ) ``` ### Embedding for Composition ```go type Logger struct { prefix string } func (l *Logger) Log(msg string) { fmt.Printf("[%s] %s\n", l.prefix, msg) } type Server struct { *Logger // Embedding - Server gets Log method addr string } func NewServer(addr string) *Server { return &Server{ Logger: &Logger{prefix: "SERVER"}, addr: addr, } } // Usage s := NewServer(":8080") s.Log("Starting...") // Calls embedded Logger.Log ``` ## Memory and Performance ### Preallocate Slices When Size is Known ```go // Bad: Grows slice multiple times func processItems(items []Item) []Result { var results []Result for _, item := range items { results = append(results, process(item)) } return results } // Good: Single allocation func processItems(items []Item) []Result { results := make([]Result, 0, len(items)) for _, item := range items { results = append(results, process(item)) } return results } ``` ### Use sync.Pool for Frequent Allocations ```go var bufferPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } func ProcessRequest(data []byte) []byte { buf := bufferPool.Get().(*bytes.Buffer) defer func() { buf.Reset() bufferPool.Put(buf) }() buf.Write(data) // Process... return buf.Bytes() } ``` ### Avoid String Concatenation in Loops ```go // Bad: Creates many string allocations func join(parts []string) string { var result string for _, p := range parts { result += p + "," } return result } // Good: Single allocation with strings.Builder func join(parts []string) string { var sb strings.Builder for i, p := range parts { if i > 0 { sb.WriteString(",") } sb.WriteString(p) } return sb.String() } // Best: Use standard library func join(parts []string) string { return strings.Join(parts, ",") } ``` ## Go Tooling Integration ### Essential Commands ```bash # Build and run go build ./... go run ./cmd/myapp # Testing go test ./... go test -race ./... go test -cover ./... # Static analysis go vet ./... staticcheck ./... golangci-lint run # Module management go mod tidy go mod verify # Formatting gofmt -w . goimports -w . ``` ### Recommended Linter Configuration (.golangci.yml) ```yaml linters: enable: - errcheck - gosimple - govet - ineffassign - staticcheck - unused - gofmt - goimports - misspell - unconvert - unparam linters-settings: errcheck: check-type-assertions: true govet: check-shadowing: true issues: exclude-use-default: false ``` ## Quick Reference: Go Idioms | Idiom | Description | |-------|-------------| | Accept interfaces, return structs | Functions accept interface params, return concrete types | | Errors are values | Treat errors as first-class values, not exceptions | | Don't communicate by sharing memory | Use channels for coordination between goroutines | | Make the zero value useful | Types should work without explicit initialization | | A little copying is better than a little dependency | Avoid unnecessary external dependencies | | Clear is better than clever | Prioritize readability over cleverness | | gofmt is no one's favorite but everyone's friend | Always format with gofmt/goimports | | Return early | Handle errors first, keep happy path unindented | ## Anti-Patterns to Avoid ```go // Bad: Naked returns in long functions func process() (result int, err error) { // ... 50 lines ... return // What is being returned? } // Bad: Using panic for control flow func GetUser(id string) *User { user, err := db.Find(id) if err != nil { panic(err) // Don't do this } return user } // Bad: Passing context in struct type Request struct { ctx context.Context // Context should be first param ID string } // Good: Context as first parameter func ProcessRequest(ctx context.Context, id string) error { // ... } // Bad: Mixing value and pointer receivers type Counter struct{ n int } func (c Counter) Value() int { return c.n } // Value receiver func (c *Counter) Increment() { c.n++ } // Pointer receiver // Pick one style and be consistent ``` **Remember**: Go code should be boring in the best way - predictable, consistent, and easy to understand. When in doubt, keep it simple. ================================================ FILE: .claude/skills/golang-pro/SKILL.md ================================================ --- name: golang-pro description: Use when building Go applications requiring concurrent programming, microservices architecture, or high-performance systems. Invoke for goroutines, channels, Go generics, gRPC integration. license: MIT metadata: author: https://github.com/Jeffallan version: "1.0.0" domain: language triggers: Go, Golang, goroutines, channels, gRPC, microservices Go, Go generics, concurrent programming, Go interfaces role: specialist scope: implementation output-format: code related-skills: devops-engineer, microservices-architect, test-master --- # Golang Pro Senior Go developer with deep expertise in Go 1.21+, concurrent programming, and cloud-native microservices. Specializes in idiomatic patterns, performance optimization, and production-grade systems. ## Role Definition You are a senior Go engineer with 8+ years of systems programming experience. You specialize in Go 1.21+ with generics, concurrent patterns, gRPC microservices, and cloud-native applications. You build efficient, type-safe systems following Go proverbs. ## When to Use This Skill - Building concurrent Go applications with goroutines and channels - Implementing microservices with gRPC or REST APIs - Creating CLI tools and system utilities - Optimizing Go code for performance and memory efficiency - Designing interfaces and using Go generics - Setting up testing with table-driven tests and benchmarks ## Core Workflow 1. **Analyze architecture** - Review module structure, interfaces, concurrency patterns 2. **Design interfaces** - Create small, focused interfaces with composition 3. **Implement** - Write idiomatic Go with proper error handling and context propagation 4. **Optimize** - Profile with pprof, write benchmarks, eliminate allocations 5. **Test** - Table-driven tests, race detector, fuzzing, 80%+ coverage ## Reference Guide Load detailed guidance based on context: | Topic | Reference | Load When | |-------|-----------|-----------| | Concurrency | `references/concurrency.md` | Goroutines, channels, select, sync primitives | | Interfaces | `references/interfaces.md` | Interface design, io.Reader/Writer, composition | | Generics | `references/generics.md` | Type parameters, constraints, generic patterns | | Testing | `references/testing.md` | Table-driven tests, benchmarks, fuzzing | | Project Structure | `references/project-structure.md` | Module layout, internal packages, go.mod | ## Constraints ### MUST DO - Use gofmt and golangci-lint on all code - Add context.Context to all blocking operations - Handle all errors explicitly (no naked returns) - Write table-driven tests with subtests - Document all exported functions, types, and packages - Use `X | Y` union constraints for generics (Go 1.18+) - Propagate errors with fmt.Errorf("%w", err) - Run race detector on tests (-race flag) ### MUST NOT DO - Ignore errors (avoid _ assignment without justification) - Use panic for normal error handling - Create goroutines without clear lifecycle management - Skip context cancellation handling - Use reflection without performance justification - Mix sync and async patterns carelessly - Hardcode configuration (use functional options or env vars) ## Output Templates When implementing Go features, provide: 1. Interface definitions (contracts first) 2. Implementation files with proper package structure 3. Test file with table-driven tests 4. Brief explanation of concurrency patterns used ## Knowledge Reference Go 1.21+, goroutines, channels, select, sync package, generics, type parameters, constraints, io.Reader/Writer, gRPC, context, error wrapping, pprof profiling, benchmarks, table-driven tests, fuzzing, go.mod, internal packages, functional options ================================================ FILE: .claude/skills/golang-pro/references/concurrency.md ================================================ # Concurrency Patterns ## Goroutine Lifecycle Management ```go package main import ( "context" "fmt" "sync" "time" ) // Worker pool with bounded concurrency type WorkerPool struct { workers int tasks chan func() wg sync.WaitGroup } func NewWorkerPool(workers int) *WorkerPool { wp := &WorkerPool{ workers: workers, tasks: make(chan func(), workers*2), // Buffered channel } wp.start() return wp } func (wp *WorkerPool) start() { for i := 0; i < wp.workers; i++ { wp.wg.Add(1) go func() { defer wp.wg.Done() for task := range wp.tasks { task() } }() } } func (wp *WorkerPool) Submit(task func()) { wp.tasks <- task } func (wp *WorkerPool) Shutdown() { close(wp.tasks) wp.wg.Wait() } ``` ## Channel Patterns ```go // Generator pattern func generateNumbers(ctx context.Context, max int) <-chan int { out := make(chan int) go func() { defer close(out) for i := 0; i < max; i++ { select { case out <- i: case <-ctx.Done(): return } } }() return out } // Fan-out, fan-in pattern func fanOut(ctx context.Context, input <-chan int, workers int) []<-chan int { channels := make([]<-chan int, workers) for i := 0; i < workers; i++ { channels[i] = process(ctx, input) } return channels } func process(ctx context.Context, input <-chan int) <-chan int { out := make(chan int) go func() { defer close(out) for val := range input { select { case out <- val * 2: case <-ctx.Done(): return } } }() return out } func fanIn(ctx context.Context, channels ...<-chan int) <-chan int { out := make(chan int) var wg sync.WaitGroup for _, ch := range channels { wg.Add(1) go func(c <-chan int) { defer wg.Done() for val := range c { select { case out <- val: case <-ctx.Done(): return } } }(ch) } go func() { wg.Wait() close(out) }() return out } ``` ## Select Statement Patterns ```go // Timeout pattern func fetchWithTimeout(ctx context.Context, url string) (string, error) { result := make(chan string, 1) errCh := make(chan error, 1) go func() { // Simulate network call time.Sleep(100 * time.Millisecond) result <- "data from " + url }() select { case res := <-result: return res, nil case err := <-errCh: return "", err case <-time.After(50 * time.Millisecond): return "", fmt.Errorf("timeout") case <-ctx.Done(): return "", ctx.Err() } } // Done channel pattern for graceful shutdown type Server struct { done chan struct{} } func (s *Server) Shutdown() { close(s.done) } func (s *Server) Run(ctx context.Context) { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for { select { case <-ticker.C: fmt.Println("tick") case <-s.done: fmt.Println("shutting down") return case <-ctx.Done(): fmt.Println("context cancelled") return } } } ``` ## Sync Primitives ```go import "sync" // Mutex for protecting shared state type Counter struct { mu sync.Mutex count int } func (c *Counter) Increment() { c.mu.Lock() defer c.mu.Unlock() c.count++ } func (c *Counter) Value() int { c.mu.Lock() defer c.mu.Unlock() return c.count } // RWMutex for read-heavy workloads type Cache struct { mu sync.RWMutex items map[string]string } func (c *Cache) Get(key string) (string, bool) { c.mu.RLock() defer c.mu.RUnlock() val, ok := c.items[key] return val, ok } func (c *Cache) Set(key, value string) { c.mu.Lock() defer c.mu.Unlock() c.items[key] = value } // sync.Once for initialization type Service struct { once sync.Once config *Config } func (s *Service) getConfig() *Config { s.once.Do(func() { s.config = loadConfig() // Only called once }) return s.config } ``` ## Rate Limiting and Backpressure ```go import "golang.org/x/time/rate" // Token bucket rate limiter type RateLimiter struct { limiter *rate.Limiter } func NewRateLimiter(rps int) *RateLimiter { return &RateLimiter{ limiter: rate.NewLimiter(rate.Limit(rps), rps), } } func (rl *RateLimiter) Process(ctx context.Context, item string) error { if err := rl.limiter.Wait(ctx); err != nil { return err } // Process item return nil } // Semaphore pattern for limiting concurrency type Semaphore struct { slots chan struct{} } func NewSemaphore(n int) *Semaphore { return &Semaphore{ slots: make(chan struct{}, n), } } func (s *Semaphore) Acquire() { s.slots <- struct{}{} } func (s *Semaphore) Release() { <-s.slots } func (s *Semaphore) Do(fn func()) { s.Acquire() defer s.Release() fn() } ``` ## Pipeline Pattern ```go // Stage-based processing pipeline func pipeline(ctx context.Context, input <-chan int) <-chan int { // Stage 1: Square numbers stage1 := make(chan int) go func() { defer close(stage1) for num := range input { select { case stage1 <- num * num: case <-ctx.Done(): return } } }() // Stage 2: Filter even numbers stage2 := make(chan int) go func() { defer close(stage2) for num := range stage1 { if num%2 == 0 { select { case stage2 <- num: case <-ctx.Done(): return } } } }() return stage2 } ``` ## Quick Reference | Pattern | Use Case | Key Points | |---------|----------|------------| | Worker Pool | Bounded concurrency | Limit goroutines, reuse workers | | Fan-out/Fan-in | Parallel processing | Distribute work, merge results | | Pipeline | Stream processing | Chain transformations | | Rate Limiter | API throttling | Control request rate | | Semaphore | Resource limits | Cap concurrent operations | | Done Channel | Graceful shutdown | Signal completion | ================================================ FILE: .claude/skills/golang-pro/references/generics.md ================================================ # Generics and Type Parameters ## Basic Type Parameters ```go package main // Generic function with type parameter func Max[T constraints.Ordered](a, b T) T { if a > b { return a } return b } // Multiple type parameters func Map[T, U any](slice []T, fn func(T) U) []U { result := make([]U, len(slice)) for i, v := range slice { result[i] = fn(v) } return result } // Usage func main() { maxInt := Max(10, 20) // T = int maxFloat := Max(3.14, 2.71) // T = float64 maxString := Max("abc", "xyz") // T = string nums := []int{1, 2, 3} doubled := Map(nums, func(n int) int { return n * 2 }) strings := Map(nums, func(n int) string { return fmt.Sprintf("%d", n) }) } ``` ## Type Constraints ```go import "constraints" // Built-in constraints type Number interface { constraints.Integer | constraints.Float } func Sum[T Number](numbers []T) T { var total T for _, n := range numbers { total += n } return total } // Custom constraints with methods type Stringer interface { String() string } func PrintAll[T Stringer](items []T) { for _, item := range items { fmt.Println(item.String()) } } // Approximate constraint using ~ type Integer interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 } type MyInt int func Double[T Integer](n T) T { return n * 2 } // Works with both int and MyInt func main() { fmt.Println(Double(5)) // int fmt.Println(Double(MyInt(5))) // MyInt } ``` ## Generic Data Structures ```go // Generic Stack type Stack[T any] struct { items []T } func NewStack[T any]() *Stack[T] { return &Stack[T]{ items: make([]T, 0), } } func (s *Stack[T]) Push(item T) { s.items = append(s.items, item) } func (s *Stack[T]) Pop() (T, bool) { if len(s.items) == 0 { var zero T return zero, false } item := s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1] return item, true } func (s *Stack[T]) IsEmpty() bool { return len(s.items) == 0 } // Usage intStack := NewStack[int]() intStack.Push(1) intStack.Push(2) stringStack := NewStack[string]() stringStack.Push("hello") stringStack.Push("world") ``` ## Generic Map Operations ```go // Filter with generics func Filter[T any](slice []T, predicate func(T) bool) []T { result := make([]T, 0, len(slice)) for _, v := range slice { if predicate(v) { result = append(result, v) } } return result } // Reduce/Fold func Reduce[T, U any](slice []T, initial U, fn func(U, T) U) U { acc := initial for _, v := range slice { acc = fn(acc, v) } return acc } // Keys from map func Keys[K comparable, V any](m map[K]V) []K { keys := make([]K, 0, len(m)) for k := range m { keys = append(keys, k) } return keys } // Values from map func Values[K comparable, V any](m map[K]V) []V { values := make([]V, 0, len(m)) for _, v := range m { values = append(values, v) } return values } // Usage numbers := []int{1, 2, 3, 4, 5, 6} evens := Filter(numbers, func(n int) bool { return n%2 == 0 }) sum := Reduce(numbers, 0, func(acc, n int) int { return acc + n }) m := map[string]int{"a": 1, "b": 2} keys := Keys(m) // []string{"a", "b"} values := Values(m) // []int{1, 2} ``` ## Generic Pairs and Tuples ```go // Generic Pair type Pair[T, U any] struct { First T Second U } func NewPair[T, U any](first T, second U) Pair[T, U] { return Pair[T, U]{First: first, Second: second} } func (p Pair[T, U]) Swap() Pair[U, T] { return Pair[U, T]{First: p.Second, Second: p.First} } // Usage pair := NewPair("name", 42) swapped := pair.Swap() // Pair[int, string] // Generic Result type (like Rust's Result) type Result[T any] struct { value T err error } func Ok[T any](value T) Result[T] { return Result[T]{value: value} } func Err[T any](err error) Result[T] { return Result[T]{err: err} } func (r Result[T]) IsOk() bool { return r.err == nil } func (r Result[T]) Unwrap() (T, error) { return r.value, r.err } func (r Result[T]) UnwrapOr(defaultValue T) T { if r.err != nil { return defaultValue } return r.value } ``` ## Comparable Constraint ```go // Find using comparable func Find[T comparable](slice []T, target T) (int, bool) { for i, v := range slice { if v == target { return i, true } } return -1, false } // Contains func Contains[T comparable](slice []T, target T) bool { _, found := Find(slice, target) return found } // Unique elements func Unique[T comparable](slice []T) []T { seen := make(map[T]struct{}) result := make([]T, 0, len(slice)) for _, v := range slice { if _, exists := seen[v]; !exists { seen[v] = struct{}{} result = append(result, v) } } return result } // Usage nums := []int{1, 2, 2, 3, 3, 4} unique := Unique(nums) // []int{1, 2, 3, 4} idx, found := Find([]string{"a", "b", "c"}, "b") // 1, true ``` ## Generic Interfaces ```go // Generic interface type Container[T any] interface { Add(item T) Remove() (T, bool) Size() int } // Implementation type Queue[T any] struct { items []T } func (q *Queue[T]) Add(item T) { q.items = append(q.items, item) } func (q *Queue[T]) Remove() (T, bool) { if len(q.items) == 0 { var zero T return zero, false } item := q.items[0] q.items = q.items[1:] return item, true } func (q *Queue[T]) Size() int { return len(q.items) } // Function accepting generic interface func ProcessContainer[T any](c Container[T], item T) { c.Add(item) fmt.Printf("Container size: %d\n", c.Size()) } ``` ## Type Inference ```go // Type inference works in most cases func Identity[T any](x T) T { return x } // No need to specify type result := Identity(42) // T inferred as int str := Identity("hello") // T inferred as string // Type inference with constraints func Min[T constraints.Ordered](a, b T) T { if a < b { return a } return b } // Inferred from arguments minVal := Min(10, 20) // T = int minFloat := Min(1.5, 2.5) // T = float64 // Explicit type when needed result := Map[int, string]([]int{1, 2}, func(n int) string { return fmt.Sprintf("%d", n) }) ``` ## Generic Channels ```go // Generic channel operations func Merge[T any](channels ...<-chan T) <-chan T { out := make(chan T) var wg sync.WaitGroup for _, ch := range channels { wg.Add(1) go func(c <-chan T) { defer wg.Done() for v := range c { out <- v } }(ch) } go func() { wg.Wait() close(out) }() return out } // Generic pipeline stage func Stage[T, U any](in <-chan T, fn func(T) U) <-chan U { out := make(chan U) go func() { defer close(out) for v := range in { out <- fn(v) } }() return out } // Usage ch1 := make(chan int) ch2 := make(chan int) merged := Merge(ch1, ch2) numbers := make(chan int) doubled := Stage(numbers, func(n int) int { return n * 2 }) strings := Stage(doubled, func(n int) string { return fmt.Sprintf("%d", n) }) ``` ## Union Constraints ```go // Union of types type StringOrInt interface { string | int } func Process[T StringOrInt](val T) string { return fmt.Sprintf("%v", val) } // More complex unions type Numeric interface { int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64 } func Abs[T Numeric](n T) T { if n < 0 { return -n } return n } // Union with methods type Serializable interface { string | []byte } func Serialize[T Serializable](data T) []byte { switch v := any(data).(type) { case string: return []byte(v) case []byte: return v default: panic("unreachable") } } ``` ## Quick Reference | Feature | Syntax | Use Case | |---------|--------|----------| | Basic generic | `func F[T any]()` | Any type | | Constraint | `func F[T Constraint]()` | Restricted types | | Multiple params | `func F[T, U any]()` | Multiple type variables | | Comparable | `func F[T comparable]()` | Types supporting == and != | | Ordered | `func F[T constraints.Ordered]()` | Types supporting <, >, <=, >= | | Union | `T interface{int \| string}` | Either type | | Approximate | `~int` | Include type aliases | ================================================ FILE: .claude/skills/golang-pro/references/interfaces.md ================================================ # Interface Design and Composition ## Small, Focused Interfaces ```go // Single-method interfaces (idiomatic Go) type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } type Closer interface { Close() error } // Interface composition type ReadCloser interface { Reader Closer } type WriteCloser interface { Writer Closer } type ReadWriteCloser interface { Reader Writer Closer } ``` ## Accept Interfaces, Return Structs ```go package storage import "io" // Storage is the concrete type (struct) type Storage struct { baseDir string } // NewStorage returns a concrete type func NewStorage(baseDir string) *Storage { return &Storage{baseDir: baseDir} } // SaveFile accepts an interface for flexibility func (s *Storage) SaveFile(filename string, data io.Reader) error { // Implementation can work with any Reader // (file, network, buffer, etc.) return nil } // Usage allows dependency injection type Uploader interface { SaveFile(filename string, data io.Reader) error } type Service struct { uploader Uploader // Accept interface } // NewService accepts interface for testing flexibility func NewService(uploader Uploader) *Service { return &Service{uploader: uploader} } ``` ## io.Reader and io.Writer Patterns ```go import ( "io" "strings" ) // Chain readers with io.MultiReader func combineReaders() io.Reader { r1 := strings.NewReader("Hello ") r2 := strings.NewReader("World") return io.MultiReader(r1, r2) } // Tee reader for duplicating reads func duplicateRead(r io.Reader, w io.Writer) io.Reader { return io.TeeReader(r, w) // Writes to w while reading from r } // Limit reader to prevent reading too much func limitedRead(r io.Reader, n int64) io.Reader { return io.LimitReader(r, n) } // Custom Reader implementation type UppercaseReader struct { src io.Reader } func (u *UppercaseReader) Read(p []byte) (n int, err error) { n, err = u.src.Read(p) for i := 0; i < n; i++ { if p[i] >= 'a' && p[i] <= 'z' { p[i] = p[i] - 32 } } return n, err } // Custom Writer implementation type CountingWriter struct { w io.Writer count int64 } func (cw *CountingWriter) Write(p []byte) (n int, err error) { n, err = cw.w.Write(p) cw.count += int64(n) return n, err } func (cw *CountingWriter) BytesWritten() int64 { return cw.count } ``` ## Embedding for Composition ```go import "sync" // Embed to extend behavior type SafeCounter struct { mu sync.Mutex m map[string]int } func (sc *SafeCounter) Inc(key string) { sc.mu.Lock() defer sc.mu.Unlock() sc.m[key]++ } // Embed interface to add default behavior type Logger interface { Log(msg string) } type NoOpLogger struct{} func (NoOpLogger) Log(msg string) {} type Service struct { Logger // Embedded interface (default implementation can be provided) } func NewService(logger Logger) *Service { if logger == nil { logger = NoOpLogger{} // Provide default } return &Service{Logger: logger} } // Now Service.Log() is available ``` ## Interface Satisfaction Verification ```go import "io" // Compile-time interface verification var _ io.Reader = (*MyReader)(nil) var _ io.Writer = (*MyWriter)(nil) var _ io.Closer = (*MyCloser)(nil) type MyReader struct{} func (m *MyReader) Read(p []byte) (n int, err error) { return 0, nil } type MyWriter struct{} func (m *MyWriter) Write(p []byte) (n int, err error) { return len(p), nil } type MyCloser struct{} func (m *MyCloser) Close() error { return nil } ``` ## Functional Options Pattern ```go package server import "time" type Server struct { host string port int timeout time.Duration maxConns int enableLogger bool } // Option is a functional option for configuring Server type Option func(*Server) func WithHost(host string) Option { return func(s *Server) { s.host = host } } func WithPort(port int) Option { return func(s *Server) { s.port = port } } func WithTimeout(timeout time.Duration) Option { return func(s *Server) { s.timeout = timeout } } func WithMaxConnections(max int) Option { return func(s *Server) { s.maxConns = max } } func WithLogger(enabled bool) Option { return func(s *Server) { s.enableLogger = enabled } } // NewServer creates a server with functional options func NewServer(opts ...Option) *Server { // Defaults s := &Server{ host: "localhost", port: 8080, timeout: 30 * time.Second, maxConns: 100, } // Apply options for _, opt := range opts { opt(s) } return s } // Usage: // server := NewServer( // WithHost("0.0.0.0"), // WithPort(9000), // WithTimeout(60 * time.Second), // WithLogger(true), // ) ``` ## Interface Segregation ```go // Bad: Fat interface type BadRepository interface { Create(item Item) error Read(id string) (Item, error) Update(item Item) error Delete(id string) error List() ([]Item, error) Search(query string) ([]Item, error) Count() (int, error) } // Good: Segregated interfaces type Creator interface { Create(item Item) error } type Reader interface { Read(id string) (Item, error) } type Updater interface { Update(item Item) error } type Deleter interface { Delete(id string) error } type Lister interface { List() ([]Item, error) } // Compose only what you need type ReadWriter interface { Reader Creator } type FullRepository interface { Creator Reader Updater Deleter Lister } ``` ## Type Assertions and Type Switches ```go import "fmt" // Safe type assertion func processValue(v interface{}) { // Two-value assertion (safe) if str, ok := v.(string); ok { fmt.Println("String:", str) return } // Type switch switch val := v.(type) { case int: fmt.Println("Int:", val) case string: fmt.Println("String:", val) case bool: fmt.Println("Bool:", val) default: fmt.Println("Unknown type") } } // Check for optional interface methods type Flusher interface { Flush() error } func writeAndFlush(w io.Writer, data []byte) error { if _, err := w.Write(data); err != nil { return err } // Check if Writer also implements Flusher if flusher, ok := w.(Flusher); ok { return flusher.Flush() } return nil } ``` ## Dependency Injection via Interfaces ```go package app import "context" // Define interfaces for dependencies type UserRepository interface { GetUser(ctx context.Context, id string) (*User, error) SaveUser(ctx context.Context, user *User) error } type EmailSender interface { SendEmail(ctx context.Context, to, subject, body string) error } // Service depends on interfaces type UserService struct { repo UserRepository mailer EmailSender } func NewUserService(repo UserRepository, mailer EmailSender) *UserService { return &UserService{ repo: repo, mailer: mailer, } } func (s *UserService) RegisterUser(ctx context.Context, email string) error { user := &User{Email: email} if err := s.repo.SaveUser(ctx, user); err != nil { return err } return s.mailer.SendEmail(ctx, email, "Welcome", "Thanks for registering!") } // Easy to mock in tests type MockUserRepository struct{} func (m *MockUserRepository) GetUser(ctx context.Context, id string) (*User, error) { return &User{ID: id}, nil } func (m *MockUserRepository) SaveUser(ctx context.Context, user *User) error { return nil } ``` ## Quick Reference | Pattern | Use Case | Key Principle | |---------|----------|---------------| | Small interfaces | Flexibility | Single-method interfaces | | Accept interfaces | Testability | Depend on abstractions | | Return structs | Clarity | Concrete return types | | io.Reader/Writer | I/O operations | Standard library integration | | Embedding | Composition | Extend behavior without inheritance | | Functional options | Configuration | Flexible constructors | | Type assertions | Runtime checks | Safe downcasting | ================================================ FILE: .claude/skills/golang-pro/references/project-structure.md ================================================ # Project Structure and Module Management ## Standard Project Layout ``` myproject/ ├── cmd/ # Main applications │ ├── server/ │ │ └── main.go # Entry point for server │ └── cli/ │ └── main.go # Entry point for CLI tool ├── internal/ # Private application code │ ├── api/ # API handlers │ ├── service/ # Business logic │ └── repository/ # Data access layer ├── pkg/ # Public library code │ └── models/ # Shared models ├── api/ # API definitions │ ├── openapi.yaml # OpenAPI spec │ └── proto/ # Protocol buffers ├── web/ # Web assets │ ├── static/ │ └── templates/ ├── scripts/ # Build and install scripts ├── configs/ # Configuration files ├── deployments/ # Docker, K8s configs ├── test/ # Additional test data ├── docs/ # Documentation ├── go.mod # Module definition ├── go.sum # Dependency checksums ├── Makefile # Build automation └── README.md ``` ## go.mod Basics ```go // Initialize module // go mod init github.com/user/project module github.com/user/myproject go 1.21 require ( github.com/gin-gonic/gin v1.9.1 github.com/lib/pq v1.10.9 go.uber.org/zap v1.26.0 ) require ( // Indirect dependencies (automatically managed) github.com/bytedance/sonic v1.9.1 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect ) // Replace directive for local development replace github.com/user/mylib => ../mylib // Retract directive to mark bad versions retract v1.0.1 // Contains critical bug ``` ## Module Commands ```bash # Initialize module go mod init github.com/user/project # Add missing dependencies go mod tidy # Download dependencies go mod download # Verify dependencies go mod verify # Show module graph go mod graph # Show why package is needed go mod why github.com/user/package # Vendor dependencies (copy to vendor/) go mod vendor # Update dependency go get -u github.com/user/package # Update to specific version go get github.com/user/package@v1.2.3 # Update all dependencies go get -u ./... # Remove unused dependencies go mod tidy ``` ## Internal Packages ```go // internal/ packages can only be imported by code in the parent tree myproject/ ├── internal/ │ ├── auth/ # Can only be imported by myproject │ │ └── jwt.go │ └── database/ │ └── postgres.go └── pkg/ └── models/ # Can be imported by anyone └── user.go // This works (same project): import "github.com/user/myproject/internal/auth" // This fails (different project): import "github.com/other/project/internal/auth" // Error! // Internal subdirectories myproject/ └── api/ └── internal/ # Can only be imported by code in api/ └── helpers.go ``` ## Package Organization ```go // user/user.go - Domain package package user import ( "context" "time" ) // User represents a user entity type User struct { ID string Email string CreatedAt time.Time } // Repository defines data access interface type Repository interface { Create(ctx context.Context, user *User) error GetByID(ctx context.Context, id string) (*User, error) Update(ctx context.Context, user *User) error Delete(ctx context.Context, id string) error } // Service handles business logic type Service struct { repo Repository } // NewService creates a new user service func NewService(repo Repository) *Service { return &Service{repo: repo} } func (s *Service) RegisterUser(ctx context.Context, email string) (*User, error) { user := &User{ ID: generateID(), Email: email, CreatedAt: time.Now(), } return user, s.repo.Create(ctx, user) } ``` ## Multi-Module Repository (Monorepo) ``` monorepo/ ├── go.work # Workspace file ├── services/ │ ├── api/ │ │ ├── go.mod │ │ └── main.go │ └── worker/ │ ├── go.mod │ └── main.go └── shared/ └── models/ ├── go.mod └── user.go // go.work go 1.21 use ( ./services/api ./services/worker ./shared/models ) // Commands: // go work init ./services/api ./services/worker // go work use ./shared/models // go work sync ``` ## Build Tags and Constraints ```go // +build integration // integration_test.go package myapp import "testing" func TestIntegration(t *testing.T) { // Integration test code } // Build: go test -tags=integration // File-level build constraints (Go 1.17+) //go:build linux && amd64 package myapp // Multiple constraints //go:build linux || darwin //go:build amd64 // Negation //go:build !windows // Common tags: // linux, darwin, windows, freebsd // amd64, arm64, 386, arm // cgo, !cgo ``` ## Makefile Example ```makefile # Makefile .PHONY: build test lint clean run # Variables BINARY_NAME=myapp BUILD_DIR=bin GO=go GOFLAGS=-v # Build the application build: $(GO) build $(GOFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME) ./cmd/server # Run tests test: $(GO) test -v -race -coverprofile=coverage.out ./... # Run tests with coverage report test-coverage: test $(GO) tool cover -html=coverage.out # Run linters lint: golangci-lint run ./... # Format code fmt: $(GO) fmt ./... goimports -w . # Run the application run: $(GO) run ./cmd/server # Clean build artifacts clean: rm -rf $(BUILD_DIR) rm -f coverage.out # Install dependencies deps: $(GO) mod download $(GO) mod tidy # Build for multiple platforms build-all: GOOS=linux GOARCH=amd64 $(GO) build -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 ./cmd/server GOOS=darwin GOARCH=amd64 $(GO) build -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64 ./cmd/server GOOS=windows GOARCH=amd64 $(GO) build -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/server # Run with race detector run-race: $(GO) run -race ./cmd/server # Generate code generate: $(GO) generate ./... # Docker build docker-build: docker build -t $(BINARY_NAME):latest . # Help help: @echo "Available targets:" @echo " build - Build the application" @echo " test - Run tests" @echo " test-coverage - Run tests with coverage report" @echo " lint - Run linters" @echo " fmt - Format code" @echo " run - Run the application" @echo " clean - Clean build artifacts" @echo " deps - Install dependencies" ``` ## Dockerfile Multi-Stage Build ```dockerfile # Build stage FROM golang:1.21-alpine AS builder WORKDIR /app # Copy go mod files COPY go.mod go.sum ./ RUN go mod download # Copy source code COPY . . # Build binary RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o server ./cmd/server # Final stage FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ # Copy binary from builder COPY --from=builder /app/server . # Copy config files if needed COPY --from=builder /app/configs ./configs EXPOSE 8080 CMD ["./server"] ``` ## Version Information ```go // version/version.go package version import "runtime" var ( // Set via ldflags during build Version = "dev" GitCommit = "none" BuildTime = "unknown" ) // Info returns version information func Info() map[string]string { return map[string]string{ "version": Version, "git_commit": GitCommit, "build_time": BuildTime, "go_version": runtime.Version(), "os": runtime.GOOS, "arch": runtime.GOARCH, } } // Build with version info: // go build -ldflags "-X github.com/user/project/version.Version=1.0.0 \ // -X github.com/user/project/version.GitCommit=$(git rev-parse HEAD) \ // -X github.com/user/project/version.BuildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" ``` ## Go Generate ```go // models/user.go //go:generate mockgen -source=user.go -destination=../mocks/user_mock.go -package=mocks package models type UserRepository interface { GetUser(id string) (*User, error) SaveUser(user *User) error } // tools.go - Track tool dependencies //go:build tools package tools import ( _ "github.com/golang/mock/mockgen" _ "golang.org/x/tools/cmd/stringer" ) // Install tools: // go install github.com/golang/mock/mockgen@latest // Run generate: // go generate ./... ``` ## Configuration Management ```go // config/config.go package config import ( "os" "time" "github.com/kelseyhightower/envconfig" ) type Config struct { Server ServerConfig Database DatabaseConfig Redis RedisConfig } type ServerConfig struct { Host string `envconfig:"SERVER_HOST" default:"0.0.0.0"` Port int `envconfig:"SERVER_PORT" default:"8080"` ReadTimeout time.Duration `envconfig:"SERVER_READ_TIMEOUT" default:"10s"` WriteTimeout time.Duration `envconfig:"SERVER_WRITE_TIMEOUT" default:"10s"` } type DatabaseConfig struct { URL string `envconfig:"DATABASE_URL" required:"true"` MaxOpenConns int `envconfig:"DB_MAX_OPEN_CONNS" default:"25"` MaxIdleConns int `envconfig:"DB_MAX_IDLE_CONNS" default:"5"` } type RedisConfig struct { Addr string `envconfig:"REDIS_ADDR" default:"localhost:6379"` Password string `envconfig:"REDIS_PASSWORD"` DB int `envconfig:"REDIS_DB" default:"0"` } // Load loads configuration from environment func Load() (*Config, error) { var cfg Config if err := envconfig.Process("", &cfg); err != nil { return nil, err } return &cfg, nil } ``` ## Quick Reference | Command | Description | |---------|-------------| | `go mod init` | Initialize module | | `go mod tidy` | Add/remove dependencies | | `go mod download` | Download dependencies | | `go get package@version` | Add/update dependency | | `go build -ldflags "-X ..."` | Set version info | | `go generate ./...` | Run code generation | | `GOOS=linux go build` | Cross-compile | | `go work init` | Initialize workspace | ================================================ FILE: .claude/skills/golang-pro/references/testing.md ================================================ # Testing and Benchmarking ## Table-Driven Tests ```go package math import "testing" func Add(a, b int) int { return a + b } func TestAdd(t *testing.T) { tests := []struct { name string a, b int expected int }{ {"positive numbers", 2, 3, 5}, {"negative numbers", -2, -3, -5}, {"mixed signs", -2, 3, 1}, {"zeros", 0, 0, 0}, {"large numbers", 1000000, 2000000, 3000000}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := Add(tt.a, tt.b) if result != tt.expected { t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected) } }) } } ``` ## Subtests and Parallel Execution ```go func TestParallel(t *testing.T) { tests := []struct { name string input string want string }{ {"lowercase", "hello", "HELLO"}, {"uppercase", "WORLD", "WORLD"}, {"mixed", "HeLLo", "HELLO"}, } for _, tt := range tests { tt := tt // Capture range variable for parallel tests t.Run(tt.name, func(t *testing.T) { t.Parallel() // Run subtests in parallel result := strings.ToUpper(tt.input) if result != tt.want { t.Errorf("got %q, want %q", result, tt.want) } }) } } ``` ## Test Helpers and Setup/Teardown ```go func TestWithSetup(t *testing.T) { // Setup db := setupTestDB(t) defer cleanupTestDB(t, db) tests := []struct { name string user User }{ {"valid user", User{Name: "John", Email: "john@example.com"}}, {"empty name", User{Name: "", Email: "test@example.com"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := db.SaveUser(tt.user) if err != nil { t.Fatalf("SaveUser failed: %v", err) } }) } } // Helper function (doesn't show in stack trace) func setupTestDB(t *testing.T) *DB { t.Helper() db, err := NewDB(":memory:") if err != nil { t.Fatalf("failed to create test DB: %v", err) } return db } func cleanupTestDB(t *testing.T, db *DB) { t.Helper() if err := db.Close(); err != nil { t.Errorf("failed to close DB: %v", err) } } ``` ## Mocking with Interfaces ```go // Interface to mock type EmailSender interface { Send(to, subject, body string) error } // Mock implementation type MockEmailSender struct { SentEmails []Email ShouldFail bool } type Email struct { To, Subject, Body string } func (m *MockEmailSender) Send(to, subject, body string) error { if m.ShouldFail { return fmt.Errorf("failed to send email") } m.SentEmails = append(m.SentEmails, Email{to, subject, body}) return nil } // Test using mock func TestUserService_Register(t *testing.T) { mockSender := &MockEmailSender{} service := NewUserService(mockSender) err := service.Register("user@example.com") if err != nil { t.Fatalf("Register failed: %v", err) } if len(mockSender.SentEmails) != 1 { t.Errorf("expected 1 email sent, got %d", len(mockSender.SentEmails)) } email := mockSender.SentEmails[0] if email.To != "user@example.com" { t.Errorf("expected email to user@example.com, got %s", email.To) } } ``` ## Benchmarking ```go func BenchmarkAdd(b *testing.B) { for i := 0; i < b.N; i++ { Add(100, 200) } } // Benchmark with subtests func BenchmarkStringOperations(b *testing.B) { benchmarks := []struct { name string input string }{ {"short", "hello"}, {"medium", strings.Repeat("hello", 10)}, {"long", strings.Repeat("hello", 100)}, } for _, bm := range benchmarks { b.Run(bm.name, func(b *testing.B) { for i := 0; i < b.N; i++ { _ = strings.ToUpper(bm.input) } }) } } // Benchmark with setup func BenchmarkMapOperations(b *testing.B) { m := make(map[string]int) for i := 0; i < 1000; i++ { m[fmt.Sprintf("key%d", i)] = i } b.ResetTimer() // Don't count setup time for i := 0; i < b.N; i++ { _ = m["key500"] } } // Parallel benchmark func BenchmarkConcurrentAccess(b *testing.B) { var counter int64 b.RunParallel(func(pb *testing.PB) { for pb.Next() { atomic.AddInt64(&counter, 1) } }) } // Memory allocation benchmark func BenchmarkAllocation(b *testing.B) { b.ReportAllocs() // Report allocations for i := 0; i < b.N; i++ { s := make([]int, 1000) _ = s } } ``` ## Fuzzing (Go 1.18+) ```go func FuzzReverse(f *testing.F) { // Seed corpus testcases := []string{"hello", "world", "123", ""} for _, tc := range testcases { f.Add(tc) } f.Fuzz(func(t *testing.T, input string) { reversed := Reverse(input) doubleReversed := Reverse(reversed) if input != doubleReversed { t.Errorf("Reverse(Reverse(%q)) = %q, want %q", input, doubleReversed, input) } }) } // Fuzz with multiple parameters func FuzzAdd(f *testing.F) { f.Add(1, 2) f.Add(0, 0) f.Add(-1, 1) f.Fuzz(func(t *testing.T, a, b int) { result := Add(a, b) // Properties that should always hold if result < a && b >= 0 { t.Errorf("Add(%d, %d) = %d; result should be >= a when b >= 0", a, b, result) } }) } ``` ## Test Coverage ```go // Run tests with coverage: // go test -cover // go test -coverprofile=coverage.out // go tool cover -html=coverage.out func TestCalculate(t *testing.T) { tests := []struct { name string input int expected int }{ {"zero", 0, 0}, {"positive", 5, 25}, {"negative", -3, 9}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := Calculate(tt.input) if result != tt.expected { t.Errorf("Calculate(%d) = %d; want %d", tt.input, result, tt.expected) } }) } } ``` ## Race Detector ```go // Run with: go test -race func TestConcurrentAccess(t *testing.T) { var counter int var wg sync.WaitGroup // This will fail with -race if not synchronized for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() counter++ // Data race! }() } wg.Wait() } // Fixed version with mutex func TestConcurrentAccessSafe(t *testing.T) { var counter int var mu sync.Mutex var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() mu.Lock() counter++ mu.Unlock() }() } wg.Wait() if counter != 10 { t.Errorf("expected 10, got %d", counter) } } ``` ## Golden Files ```go import ( "os" "path/filepath" "testing" ) func TestRenderHTML(t *testing.T) { data := Data{Title: "Test", Content: "Hello"} result := RenderHTML(data) goldenFile := filepath.Join("testdata", "expected.html") if *update { // Update golden file: go test -update os.WriteFile(goldenFile, []byte(result), 0644) } expected, err := os.ReadFile(goldenFile) if err != nil { t.Fatalf("failed to read golden file: %v", err) } if result != string(expected) { t.Errorf("output doesn't match golden file\ngot:\n%s\nwant:\n%s", result, expected) } } var update = flag.Bool("update", false, "update golden files") ``` ## Integration Tests ```go // integration_test.go // +build integration package myapp import ( "testing" "time" ) func TestIntegration(t *testing.T) { if testing.Short() { t.Skip("skipping integration test in short mode") } // Long-running integration test server := startTestServer(t) defer server.Stop() time.Sleep(100 * time.Millisecond) // Wait for server client := NewClient(server.URL) resp, err := client.Get("/health") if err != nil { t.Fatalf("health check failed: %v", err) } if resp.Status != "ok" { t.Errorf("expected status ok, got %s", resp.Status) } } // Run: go test -tags=integration // Run short tests only: go test -short ``` ## Testable Examples ```go // Example tests that appear in godoc func ExampleAdd() { result := Add(2, 3) fmt.Println(result) // Output: 5 } func ExampleAdd_negative() { result := Add(-2, -3) fmt.Println(result) // Output: -5 } // Unordered output func ExampleKeys() { m := map[string]int{"a": 1, "b": 2, "c": 3} keys := Keys(m) for _, k := range keys { fmt.Println(k) } // Unordered output: // a // b // c } ``` ## Quick Reference | Command | Description | |---------|-------------| | `go test` | Run tests | | `go test -v` | Verbose output | | `go test -run TestName` | Run specific test | | `go test -bench .` | Run benchmarks | | `go test -cover` | Show coverage | | `go test -race` | Run race detector | | `go test -short` | Skip long tests | | `go test -fuzz FuzzName` | Run fuzzing | | `go test -cpuprofile cpu.prof` | CPU profiling | | `go test -memprofile mem.prof` | Memory profiling | ================================================ FILE: .claude/skills/skill-creator/LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: .claude/skills/skill-creator/SKILL.md ================================================ --- name: skill-creator description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, update or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. --- # Skill Creator A skill for creating new skills and iteratively improving them. At a high level, the process of creating a skill goes like this: - Decide what you want the skill to do and roughly how it should do it - Write a draft of the skill - Create a few test prompts and run claude-with-access-to-the-skill on them - Help the user evaluate the results both qualitatively and quantitatively - While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist) - Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics - Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks) - Repeat until you're satisfied - Expand the test set and try again at larger scale Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat. On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop. Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead. Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill. Cool? Cool. ## Communicating with the user The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate. So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea: - "evaluation" and "benchmark" are borderline, but OK - for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it. --- ## Creating a skill ### Capture Intent Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step. 1. What should this skill enable Claude to do? 2. When should this skill trigger? (what user phrases/contexts) 3. What's the expected output format? 4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide. ### Interview and Research Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out. Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user. ### Write the SKILL.md Based on the user interview, fill in these components: - **name**: Skill identifier - **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently Claude has a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'" - **compatibility**: Required tools, dependencies (optional, rarely needed) - **the rest of the skill :)** ### Skill Writing Guide #### Anatomy of a Skill ``` skill-name/ ├── SKILL.md (required) │ ├── YAML frontmatter (name, description required) │ └── Markdown instructions └── Bundled Resources (optional) ├── scripts/ - Executable code for deterministic/repetitive tasks ├── references/ - Docs loaded into context as needed └── assets/ - Files used in output (templates, icons, fonts) ``` #### Progressive Disclosure Skills use a three-level loading system: 1. **Metadata** (name + description) - Always in context (~100 words) 2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal) 3. **Bundled resources** - As needed (unlimited, scripts can execute without loading) These word counts are approximate and you can feel free to go longer if needed. **Key patterns:** - Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up. - Reference files clearly from SKILL.md with guidance on when to read them - For large reference files (>300 lines), include a table of contents **Domain organization**: When a skill supports multiple domains/frameworks, organize by variant: ``` cloud-deploy/ ├── SKILL.md (workflow + selection) └── references/ ├── aws.md ├── gcp.md └── azure.md ``` Claude reads only the relevant reference file. #### Principle of Lack of Surprise This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though. #### Writing Patterns Prefer using the imperative form in instructions. **Defining output formats** - You can do it like this: ```markdown ## Report structure ALWAYS use this exact template: # [Title] ## Executive summary ## Key findings ## Recommendations ``` **Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little): ```markdown ## Commit message format **Example 1:** Input: Added user authentication with JWT tokens Output: feat(auth): implement JWT-based authentication ``` ### Writing Style Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it. ### Test Cases After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them. Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress. ```json { "skill_name": "example-skill", "evals": [ { "id": 1, "prompt": "User's task prompt", "expected_output": "Description of expected result", "files": [] } ] } ``` See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later). ## Running and evaluating test cases This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill. Put results in `-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go. ### Step 1: Spawn all runs (with-skill AND baseline) in the same turn For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time. **With-skill run:** ``` Execute this task: - Skill path: - Task: - Input files: - Save outputs to: /iteration-/eval-/with_skill/outputs/ - Outputs to save: ``` **Baseline run** (same prompt, but the baseline depends on context): - **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`. - **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r /skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`. Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations. ```json { "eval_id": 0, "eval_name": "descriptive-name-here", "prompt": "The user's task prompt", "assertions": [] } ``` ### Step 2: While runs are in progress, draft assertions Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check. Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment. Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark. ### Step 3: As runs complete, capture timing data When each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory: ```json { "total_tokens": 84852, "duration_ms": 23332, "total_duration_seconds": 23.3 } ``` This is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them. ### Step 4: Grade, aggregate, and launch the viewer Once all runs are done: 1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations. 2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory: ```bash python -m scripts.aggregate_benchmark /iteration-N --skill-name ``` This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects. Put each with_skill version before its baseline counterpart. 3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs. 4. **Launch the viewer** with both qualitative outputs and quantitative data: ```bash nohup python /eval-viewer/generate_review.py \ /iteration-N \ --skill-name "my-skill" \ --benchmark /iteration-N/benchmark.json \ > /dev/null 2>&1 & VIEWER_PID=$! ``` For iteration 2+, also pass `--previous-workspace /iteration-`. **Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static ` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks "Submit All Reviews". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up. Note: please use generate_review.py to create the viewer; there's no need to write custom HTML. 5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know." ### What the user sees in the viewer The "Outputs" tab shows one test case at a time: - **Prompt**: the task that was given - **Output**: the files the skill produced, rendered inline where possible - **Previous Output** (iteration 2+): collapsed section showing last iteration's output - **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail - **Feedback**: a textbox that auto-saves as they type - **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations. Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`. ### Step 5: Read the feedback When the user tells you they're done, read `feedback.json`: ```json { "reviews": [ {"run_id": "eval-0-with_skill", "feedback": "the chart is missing axis labels", "timestamp": "..."}, {"run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..."}, {"run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..."} ], "status": "complete" } ``` Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints. Kill the viewer server when you're done with it: ```bash kill $VIEWER_PID 2>/dev/null ``` --- ## Improving the skill This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback. ### How to think about improvements 1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great. 2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens. 3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach. 4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel. This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need. ### The iteration loop After improving the skill: 1. Apply your improvements to the skill 2. Rerun all test cases into a new `iteration-/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration. 3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration 4. Wait for the user to review and tell you they're done 5. Read the new feedback, improve again, repeat Keep going until: - The user says they're happy - The feedback is all empty (everything looks good) - You're not making meaningful progress --- ## Advanced: Blind comparison For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won. This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient. --- ## Description Optimization The description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy. ### Step 1: Generate trigger eval queries Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON: ```json [ {"query": "the user prompt", "should_trigger": true}, {"query": "another prompt", "should_trigger": false} ] ``` The queries must be realistic and something a Claude Code or Claude.ai user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them). Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"` Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"` For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win. For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate. The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky. ### Step 2: Review with user Present the eval set to the user for review using the HTML template: 1. Read the template from `assets/eval_review.html` 2. Replace the placeholders: - `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment) - `__SKILL_NAME_PLACEHOLDER__` → the skill's name - `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description 3. Write to a temp file (e.g., `/tmp/eval_review_.html`) and open it: `open /tmp/eval_review_.html` 4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set" 5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`) This step matters — bad eval queries lead to bad descriptions. ### Step 3: Run the optimization loop Tell the user: "This will take some time — I'll run the optimization loop in the background and check on it periodically." Save the eval set to the workspace, then run in the background: ```bash python -m scripts.run_loop \ --eval-set \ --skill-path \ --model \ --max-iterations 5 \ --verbose ``` Use the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences. While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like. This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude with extended thinking to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting. ### How skill triggering works Understanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches. This means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality. ### Step 4: Apply the result Take `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores. --- ### Package and Present (only if `present_files` tool is available) Check whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user: ```bash python -m scripts.package_skill ``` After packaging, direct the user to the resulting `.skill` file path so they can install it. --- ## Claude.ai-specific instructions In Claude.ai, the core workflow is the same (draft → test → review → improve → repeat), but because Claude.ai doesn't have subagents, some mechanics change. Here's what to adapt: **Running test cases**: No subagents means no parallel execution. For each test case, read the skill's SKILL.md, then follow its instructions to accomplish the test prompt yourself. Do them one at a time. This is less rigorous than independent subagents (you wrote the skill and you're also running it, so you have full context), but it's a useful sanity check — and the human review step compensates. Skip the baseline runs — just use the skill to complete the task as requested. **Reviewing results**: If you can't open a browser (e.g., Claude.ai's VM has no display, or you're on a remote server), skip the browser reviewer entirely. Instead, present results directly in the conversation. For each test case, show the prompt and the output. If the output is a file the user needs to see (like a .docx or .xlsx), save it to the filesystem and tell them where it is so they can download and inspect it. Ask for feedback inline: "How does this look? Anything you'd change?" **Benchmarking**: Skip the quantitative benchmarking — it relies on baseline comparisons which aren't meaningful without subagents. Focus on qualitative feedback from the user. **The iteration loop**: Same as before — improve the skill, rerun the test cases, ask for feedback — just without the browser reviewer in the middle. You can still organize results into iteration directories on the filesystem if you have one. **Description optimization**: This section requires the `claude` CLI tool (specifically `claude -p`) which is only available in Claude Code. Skip it if you're on Claude.ai. **Blind comparison**: Requires subagents. Skip it. **Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. On Claude.ai, you can run it and the user can download the resulting `.skill` file. --- ## Cowork-Specific Instructions If you're in Cowork, the main things to know are: - You have subagents, so the main workflow (spawn test cases in parallel, run baselines, grade, etc.) all works. (However, if you run into severe problems with timeouts, it's OK to run the test prompts in series rather than parallel.) - You don't have a browser or display, so when generating the eval viewer, use `--static ` to write a standalone HTML file instead of starting a server. Then proffer a link that the user can click to open the HTML in their browser. - For whatever reason, the Cowork setup seems to disincline Claude from generating the eval viewer after running the tests, so just to reiterate: whether you're in Cowork or in Claude Code, after running tests, you should always generate the eval viewer for the human to look at examples before revising the skill yourself and trying to make corrections, using `generate_review.py` (not writing your own boutique html code). Sorry in advance but I'm gonna go all caps here: GENERATE THE EVAL VIEWER *BEFORE* evaluating inputs yourself. You want to get them in front of the human ASAP! - Feedback works differently: since there's no running server, the viewer's "Submit All Reviews" button will download `feedback.json` as a file. You can then read it from there (you may have to request access first). - Packaging works — `package_skill.py` just needs Python and a filesystem. - Description optimization (`run_loop.py` / `run_eval.py`) should work in Cowork just fine since it uses `claude -p` via subprocess, not a browser, but please save it until you've fully finished making the skill and the user agrees it's in good shape. --- ## Reference files The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent. - `agents/grader.md` — How to evaluate assertions against outputs - `agents/comparator.md` — How to do blind A/B comparison between two outputs - `agents/analyzer.md` — How to analyze why one version beat another The references/ directory has additional documentation: - `references/schemas.md` — JSON structures for evals.json, grading.json, etc. --- Repeating one more time the core loop here for emphasis: - Figure out what the skill is about - Draft or edit the skill - Run claude-with-access-to-the-skill on test prompts - With the user, evaluate the outputs: - Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them - Run quantitative evals - Repeat until you and the user are satisfied - Package the final skill and return it to the user. Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put "Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases" in your TodoList to make sure it happens. Good luck! ================================================ FILE: .claude/skills/skill-creator/agents/analyzer.md ================================================ # Post-hoc Analyzer Agent Analyze blind comparison results to understand WHY the winner won and generate improvement suggestions. ## Role After the blind comparator determines a winner, the Post-hoc Analyzer "unblids" the results by examining the skills and transcripts. The goal is to extract actionable insights: what made the winner better, and how can the loser be improved? ## Inputs You receive these parameters in your prompt: - **winner**: "A" or "B" (from blind comparison) - **winner_skill_path**: Path to the skill that produced the winning output - **winner_transcript_path**: Path to the execution transcript for the winner - **loser_skill_path**: Path to the skill that produced the losing output - **loser_transcript_path**: Path to the execution transcript for the loser - **comparison_result_path**: Path to the blind comparator's output JSON - **output_path**: Where to save the analysis results ## Process ### Step 1: Read Comparison Result 1. Read the blind comparator's output at comparison_result_path 2. Note the winning side (A or B), the reasoning, and any scores 3. Understand what the comparator valued in the winning output ### Step 2: Read Both Skills 1. Read the winner skill's SKILL.md and key referenced files 2. Read the loser skill's SKILL.md and key referenced files 3. Identify structural differences: - Instructions clarity and specificity - Script/tool usage patterns - Example coverage - Edge case handling ### Step 3: Read Both Transcripts 1. Read the winner's transcript 2. Read the loser's transcript 3. Compare execution patterns: - How closely did each follow their skill's instructions? - What tools were used differently? - Where did the loser diverge from optimal behavior? - Did either encounter errors or make recovery attempts? ### Step 4: Analyze Instruction Following For each transcript, evaluate: - Did the agent follow the skill's explicit instructions? - Did the agent use the skill's provided tools/scripts? - Were there missed opportunities to leverage skill content? - Did the agent add unnecessary steps not in the skill? Score instruction following 1-10 and note specific issues. ### Step 5: Identify Winner Strengths Determine what made the winner better: - Clearer instructions that led to better behavior? - Better scripts/tools that produced better output? - More comprehensive examples that guided edge cases? - Better error handling guidance? Be specific. Quote from skills/transcripts where relevant. ### Step 6: Identify Loser Weaknesses Determine what held the loser back: - Ambiguous instructions that led to suboptimal choices? - Missing tools/scripts that forced workarounds? - Gaps in edge case coverage? - Poor error handling that caused failures? ### Step 7: Generate Improvement Suggestions Based on the analysis, produce actionable suggestions for improving the loser skill: - Specific instruction changes to make - Tools/scripts to add or modify - Examples to include - Edge cases to address Prioritize by impact. Focus on changes that would have changed the outcome. ### Step 8: Write Analysis Results Save structured analysis to `{output_path}`. ## Output Format Write a JSON file with this structure: ```json { "comparison_summary": { "winner": "A", "winner_skill": "path/to/winner/skill", "loser_skill": "path/to/loser/skill", "comparator_reasoning": "Brief summary of why comparator chose winner" }, "winner_strengths": [ "Clear step-by-step instructions for handling multi-page documents", "Included validation script that caught formatting errors", "Explicit guidance on fallback behavior when OCR fails" ], "loser_weaknesses": [ "Vague instruction 'process the document appropriately' led to inconsistent behavior", "No script for validation, agent had to improvise and made errors", "No guidance on OCR failure, agent gave up instead of trying alternatives" ], "instruction_following": { "winner": { "score": 9, "issues": [ "Minor: skipped optional logging step" ] }, "loser": { "score": 6, "issues": [ "Did not use the skill's formatting template", "Invented own approach instead of following step 3", "Missed the 'always validate output' instruction" ] } }, "improvement_suggestions": [ { "priority": "high", "category": "instructions", "suggestion": "Replace 'process the document appropriately' with explicit steps: 1) Extract text, 2) Identify sections, 3) Format per template", "expected_impact": "Would eliminate ambiguity that caused inconsistent behavior" }, { "priority": "high", "category": "tools", "suggestion": "Add validate_output.py script similar to winner skill's validation approach", "expected_impact": "Would catch formatting errors before final output" }, { "priority": "medium", "category": "error_handling", "suggestion": "Add fallback instructions: 'If OCR fails, try: 1) different resolution, 2) image preprocessing, 3) manual extraction'", "expected_impact": "Would prevent early failure on difficult documents" } ], "transcript_insights": { "winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script -> Fixed 2 issues -> Produced output", "loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods -> No validation -> Output had errors" } } ``` ## Guidelines - **Be specific**: Quote from skills and transcripts, don't just say "instructions were unclear" - **Be actionable**: Suggestions should be concrete changes, not vague advice - **Focus on skill improvements**: The goal is to improve the losing skill, not critique the agent - **Prioritize by impact**: Which changes would most likely have changed the outcome? - **Consider causation**: Did the skill weakness actually cause the worse output, or is it incidental? - **Stay objective**: Analyze what happened, don't editorialize - **Think about generalization**: Would this improvement help on other evals too? ## Categories for Suggestions Use these categories to organize improvement suggestions: | Category | Description | |----------|-------------| | `instructions` | Changes to the skill's prose instructions | | `tools` | Scripts, templates, or utilities to add/modify | | `examples` | Example inputs/outputs to include | | `error_handling` | Guidance for handling failures | | `structure` | Reorganization of skill content | | `references` | External docs or resources to add | ## Priority Levels - **high**: Would likely change the outcome of this comparison - **medium**: Would improve quality but may not change win/loss - **low**: Nice to have, marginal improvement --- # Analyzing Benchmark Results When analyzing benchmark results, the analyzer's purpose is to **surface patterns and anomalies** across multiple runs, not suggest skill improvements. ## Role Review all benchmark run results and generate freeform notes that help the user understand skill performance. Focus on patterns that wouldn't be visible from aggregate metrics alone. ## Inputs You receive these parameters in your prompt: - **benchmark_data_path**: Path to the in-progress benchmark.json with all run results - **skill_path**: Path to the skill being benchmarked - **output_path**: Where to save the notes (as JSON array of strings) ## Process ### Step 1: Read Benchmark Data 1. Read the benchmark.json containing all run results 2. Note the configurations tested (with_skill, without_skill) 3. Understand the run_summary aggregates already calculated ### Step 2: Analyze Per-Assertion Patterns For each expectation across all runs: - Does it **always pass** in both configurations? (may not differentiate skill value) - Does it **always fail** in both configurations? (may be broken or beyond capability) - Does it **always pass with skill but fail without**? (skill clearly adds value here) - Does it **always fail with skill but pass without**? (skill may be hurting) - Is it **highly variable**? (flaky expectation or non-deterministic behavior) ### Step 3: Analyze Cross-Eval Patterns Look for patterns across evals: - Are certain eval types consistently harder/easier? - Do some evals show high variance while others are stable? - Are there surprising results that contradict expectations? ### Step 4: Analyze Metrics Patterns Look at time_seconds, tokens, tool_calls: - Does the skill significantly increase execution time? - Is there high variance in resource usage? - Are there outlier runs that skew the aggregates? ### Step 5: Generate Notes Write freeform observations as a list of strings. Each note should: - State a specific observation - Be grounded in the data (not speculation) - Help the user understand something the aggregate metrics don't show Examples: - "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value" - "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure that may be flaky" - "Without-skill runs consistently fail on table extraction expectations (0% pass rate)" - "Skill adds 13s average execution time but improves pass rate by 50%" - "Token usage is 80% higher with skill, primarily due to script output parsing" - "All 3 without-skill runs for eval 1 produced empty output" ### Step 6: Write Notes Save notes to `{output_path}` as a JSON array of strings: ```json [ "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value", "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure", "Without-skill runs consistently fail on table extraction expectations", "Skill adds 13s average execution time but improves pass rate by 50%" ] ``` ## Guidelines **DO:** - Report what you observe in the data - Be specific about which evals, expectations, or runs you're referring to - Note patterns that aggregate metrics would hide - Provide context that helps interpret the numbers **DO NOT:** - Suggest improvements to the skill (that's for the improvement step, not benchmarking) - Make subjective quality judgments ("the output was good/bad") - Speculate about causes without evidence - Repeat information already in the run_summary aggregates ================================================ FILE: .claude/skills/skill-creator/agents/comparator.md ================================================ # Blind Comparator Agent Compare two outputs WITHOUT knowing which skill produced them. ## Role The Blind Comparator judges which output better accomplishes the eval task. You receive two outputs labeled A and B, but you do NOT know which skill produced which. This prevents bias toward a particular skill or approach. Your judgment is based purely on output quality and task completion. ## Inputs You receive these parameters in your prompt: - **output_a_path**: Path to the first output file or directory - **output_b_path**: Path to the second output file or directory - **eval_prompt**: The original task/prompt that was executed - **expectations**: List of expectations to check (optional - may be empty) ## Process ### Step 1: Read Both Outputs 1. Examine output A (file or directory) 2. Examine output B (file or directory) 3. Note the type, structure, and content of each 4. If outputs are directories, examine all relevant files inside ### Step 2: Understand the Task 1. Read the eval_prompt carefully 2. Identify what the task requires: - What should be produced? - What qualities matter (accuracy, completeness, format)? - What would distinguish a good output from a poor one? ### Step 3: Generate Evaluation Rubric Based on the task, generate a rubric with two dimensions: **Content Rubric** (what the output contains): | Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) | |-----------|----------|----------------|---------------| | Correctness | Major errors | Minor errors | Fully correct | | Completeness | Missing key elements | Mostly complete | All elements present | | Accuracy | Significant inaccuracies | Minor inaccuracies | Accurate throughout | **Structure Rubric** (how the output is organized): | Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) | |-----------|----------|----------------|---------------| | Organization | Disorganized | Reasonably organized | Clear, logical structure | | Formatting | Inconsistent/broken | Mostly consistent | Professional, polished | | Usability | Difficult to use | Usable with effort | Easy to use | Adapt criteria to the specific task. For example: - PDF form → "Field alignment", "Text readability", "Data placement" - Document → "Section structure", "Heading hierarchy", "Paragraph flow" - Data output → "Schema correctness", "Data types", "Completeness" ### Step 4: Evaluate Each Output Against the Rubric For each output (A and B): 1. **Score each criterion** on the rubric (1-5 scale) 2. **Calculate dimension totals**: Content score, Structure score 3. **Calculate overall score**: Average of dimension scores, scaled to 1-10 ### Step 5: Check Assertions (if provided) If expectations are provided: 1. Check each expectation against output A 2. Check each expectation against output B 3. Count pass rates for each output 4. Use expectation scores as secondary evidence (not the primary decision factor) ### Step 6: Determine the Winner Compare A and B based on (in priority order): 1. **Primary**: Overall rubric score (content + structure) 2. **Secondary**: Assertion pass rates (if applicable) 3. **Tiebreaker**: If truly equal, declare a TIE Be decisive - ties should be rare. One output is usually better, even if marginally. ### Step 7: Write Comparison Results Save results to a JSON file at the path specified (or `comparison.json` if not specified). ## Output Format Write a JSON file with this structure: ```json { "winner": "A", "reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.", "rubric": { "A": { "content": { "correctness": 5, "completeness": 5, "accuracy": 4 }, "structure": { "organization": 4, "formatting": 5, "usability": 4 }, "content_score": 4.7, "structure_score": 4.3, "overall_score": 9.0 }, "B": { "content": { "correctness": 3, "completeness": 2, "accuracy": 3 }, "structure": { "organization": 3, "formatting": 2, "usability": 3 }, "content_score": 2.7, "structure_score": 2.7, "overall_score": 5.4 } }, "output_quality": { "A": { "score": 9, "strengths": ["Complete solution", "Well-formatted", "All fields present"], "weaknesses": ["Minor style inconsistency in header"] }, "B": { "score": 5, "strengths": ["Readable output", "Correct basic structure"], "weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"] } }, "expectation_results": { "A": { "passed": 4, "total": 5, "pass_rate": 0.80, "details": [ {"text": "Output includes name", "passed": true}, {"text": "Output includes date", "passed": true}, {"text": "Format is PDF", "passed": true}, {"text": "Contains signature", "passed": false}, {"text": "Readable text", "passed": true} ] }, "B": { "passed": 3, "total": 5, "pass_rate": 0.60, "details": [ {"text": "Output includes name", "passed": true}, {"text": "Output includes date", "passed": false}, {"text": "Format is PDF", "passed": true}, {"text": "Contains signature", "passed": false}, {"text": "Readable text", "passed": true} ] } } } ``` If no expectations were provided, omit the `expectation_results` field entirely. ## Field Descriptions - **winner**: "A", "B", or "TIE" - **reasoning**: Clear explanation of why the winner was chosen (or why it's a tie) - **rubric**: Structured rubric evaluation for each output - **content**: Scores for content criteria (correctness, completeness, accuracy) - **structure**: Scores for structure criteria (organization, formatting, usability) - **content_score**: Average of content criteria (1-5) - **structure_score**: Average of structure criteria (1-5) - **overall_score**: Combined score scaled to 1-10 - **output_quality**: Summary quality assessment - **score**: 1-10 rating (should match rubric overall_score) - **strengths**: List of positive aspects - **weaknesses**: List of issues or shortcomings - **expectation_results**: (Only if expectations provided) - **passed**: Number of expectations that passed - **total**: Total number of expectations - **pass_rate**: Fraction passed (0.0 to 1.0) - **details**: Individual expectation results ## Guidelines - **Stay blind**: DO NOT try to infer which skill produced which output. Judge purely on output quality. - **Be specific**: Cite specific examples when explaining strengths and weaknesses. - **Be decisive**: Choose a winner unless outputs are genuinely equivalent. - **Output quality first**: Assertion scores are secondary to overall task completion. - **Be objective**: Don't favor outputs based on style preferences; focus on correctness and completeness. - **Explain your reasoning**: The reasoning field should make it clear why you chose the winner. - **Handle edge cases**: If both outputs fail, pick the one that fails less badly. If both are excellent, pick the one that's marginally better. ================================================ FILE: .claude/skills/skill-creator/agents/grader.md ================================================ # Grader Agent Evaluate expectations against an execution transcript and outputs. ## Role The Grader reviews a transcript and output files, then determines whether each expectation passes or fails. Provide clear evidence for each judgment. You have two jobs: grade the outputs, and critique the evals themselves. A passing grade on a weak assertion is worse than useless — it creates false confidence. When you notice an assertion that's trivially satisfied, or an important outcome that no assertion checks, say so. ## Inputs You receive these parameters in your prompt: - **expectations**: List of expectations to evaluate (strings) - **transcript_path**: Path to the execution transcript (markdown file) - **outputs_dir**: Directory containing output files from execution ## Process ### Step 1: Read the Transcript 1. Read the transcript file completely 2. Note the eval prompt, execution steps, and final result 3. Identify any issues or errors documented ### Step 2: Examine Output Files 1. List files in outputs_dir 2. Read/examine each file relevant to the expectations. If outputs aren't plain text, use the inspection tools provided in your prompt — don't rely solely on what the transcript says the executor produced. 3. Note contents, structure, and quality ### Step 3: Evaluate Each Assertion For each expectation: 1. **Search for evidence** in the transcript and outputs 2. **Determine verdict**: - **PASS**: Clear evidence the expectation is true AND the evidence reflects genuine task completion, not just surface-level compliance - **FAIL**: No evidence, or evidence contradicts the expectation, or the evidence is superficial (e.g., correct filename but empty/wrong content) 3. **Cite the evidence**: Quote the specific text or describe what you found ### Step 4: Extract and Verify Claims Beyond the predefined expectations, extract implicit claims from the outputs and verify them: 1. **Extract claims** from the transcript and outputs: - Factual statements ("The form has 12 fields") - Process claims ("Used pypdf to fill the form") - Quality claims ("All fields were filled correctly") 2. **Verify each claim**: - **Factual claims**: Can be checked against the outputs or external sources - **Process claims**: Can be verified from the transcript - **Quality claims**: Evaluate whether the claim is justified 3. **Flag unverifiable claims**: Note claims that cannot be verified with available information This catches issues that predefined expectations might miss. ### Step 5: Read User Notes If `{outputs_dir}/user_notes.md` exists: 1. Read it and note any uncertainties or issues flagged by the executor 2. Include relevant concerns in the grading output 3. These may reveal problems even when expectations pass ### Step 6: Critique the Evals After grading, consider whether the evals themselves could be improved. Only surface suggestions when there's a clear gap. Good suggestions test meaningful outcomes — assertions that are hard to satisfy without actually doing the work correctly. Think about what makes an assertion *discriminating*: it passes when the skill genuinely succeeds and fails when it doesn't. Suggestions worth raising: - An assertion that passed but would also pass for a clearly wrong output (e.g., checking filename existence but not file content) - An important outcome you observed — good or bad — that no assertion covers at all - An assertion that can't actually be verified from the available outputs Keep the bar high. The goal is to flag things the eval author would say "good catch" about, not to nitpick every assertion. ### Step 7: Write Grading Results Save results to `{outputs_dir}/../grading.json` (sibling to outputs_dir). ## Grading Criteria **PASS when**: - The transcript or outputs clearly demonstrate the expectation is true - Specific evidence can be cited - The evidence reflects genuine substance, not just surface compliance (e.g., a file exists AND contains correct content, not just the right filename) **FAIL when**: - No evidence found for the expectation - Evidence contradicts the expectation - The expectation cannot be verified from available information - The evidence is superficial — the assertion is technically satisfied but the underlying task outcome is wrong or incomplete - The output appears to meet the assertion by coincidence rather than by actually doing the work **When uncertain**: The burden of proof to pass is on the expectation. ### Step 8: Read Executor Metrics and Timing 1. If `{outputs_dir}/metrics.json` exists, read it and include in grading output 2. If `{outputs_dir}/../timing.json` exists, read it and include timing data ## Output Format Write a JSON file with this structure: ```json { "expectations": [ { "text": "The output includes the name 'John Smith'", "passed": true, "evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'" }, { "text": "The spreadsheet has a SUM formula in cell B10", "passed": false, "evidence": "No spreadsheet was created. The output was a text file." }, { "text": "The assistant used the skill's OCR script", "passed": true, "evidence": "Transcript Step 2 shows: 'Tool: Bash - python ocr_script.py image.png'" } ], "summary": { "passed": 2, "failed": 1, "total": 3, "pass_rate": 0.67 }, "execution_metrics": { "tool_calls": { "Read": 5, "Write": 2, "Bash": 8 }, "total_tool_calls": 15, "total_steps": 6, "errors_encountered": 0, "output_chars": 12450, "transcript_chars": 3200 }, "timing": { "executor_duration_seconds": 165.0, "grader_duration_seconds": 26.0, "total_duration_seconds": 191.0 }, "claims": [ { "claim": "The form has 12 fillable fields", "type": "factual", "verified": true, "evidence": "Counted 12 fields in field_info.json" }, { "claim": "All required fields were populated", "type": "quality", "verified": false, "evidence": "Reference section was left blank despite data being available" } ], "user_notes_summary": { "uncertainties": ["Used 2023 data, may be stale"], "needs_review": [], "workarounds": ["Fell back to text overlay for non-fillable fields"] }, "eval_feedback": { "suggestions": [ { "assertion": "The output includes the name 'John Smith'", "reason": "A hallucinated document that mentions the name would also pass — consider checking it appears as the primary contact with matching phone and email from the input" }, { "reason": "No assertion checks whether the extracted phone numbers match the input — I observed incorrect numbers in the output that went uncaught" } ], "overall": "Assertions check presence but not correctness. Consider adding content verification." } } ``` ## Field Descriptions - **expectations**: Array of graded expectations - **text**: The original expectation text - **passed**: Boolean - true if expectation passes - **evidence**: Specific quote or description supporting the verdict - **summary**: Aggregate statistics - **passed**: Count of passed expectations - **failed**: Count of failed expectations - **total**: Total expectations evaluated - **pass_rate**: Fraction passed (0.0 to 1.0) - **execution_metrics**: Copied from executor's metrics.json (if available) - **output_chars**: Total character count of output files (proxy for tokens) - **transcript_chars**: Character count of transcript - **timing**: Wall clock timing from timing.json (if available) - **executor_duration_seconds**: Time spent in executor subagent - **total_duration_seconds**: Total elapsed time for the run - **claims**: Extracted and verified claims from the output - **claim**: The statement being verified - **type**: "factual", "process", or "quality" - **verified**: Boolean - whether the claim holds - **evidence**: Supporting or contradicting evidence - **user_notes_summary**: Issues flagged by the executor - **uncertainties**: Things the executor wasn't sure about - **needs_review**: Items requiring human attention - **workarounds**: Places where the skill didn't work as expected - **eval_feedback**: Improvement suggestions for the evals (only when warranted) - **suggestions**: List of concrete suggestions, each with a `reason` and optionally an `assertion` it relates to - **overall**: Brief assessment — can be "No suggestions, evals look solid" if nothing to flag ## Guidelines - **Be objective**: Base verdicts on evidence, not assumptions - **Be specific**: Quote the exact text that supports your verdict - **Be thorough**: Check both transcript and output files - **Be consistent**: Apply the same standard to each expectation - **Explain failures**: Make it clear why evidence was insufficient - **No partial credit**: Each expectation is pass or fail, not partial ================================================ FILE: .claude/skills/skill-creator/assets/eval_review.html ================================================ Eval Set Review - __SKILL_NAME_PLACEHOLDER__

Eval Set Review: __SKILL_NAME_PLACEHOLDER__

Current description: __SKILL_DESCRIPTION_PLACEHOLDER__

Query Should Trigger Actions

================================================ FILE: .claude/skills/skill-creator/eval-viewer/generate_review.py ================================================ #!/usr/bin/env python3 """Generate and serve a review page for eval results. Reads the workspace directory, discovers runs (directories with outputs/), embeds all output data into a self-contained HTML page, and serves it via a tiny HTTP server. Feedback auto-saves to feedback.json in the workspace. Usage: python generate_review.py [--port PORT] [--skill-name NAME] python generate_review.py --previous-feedback /path/to/old/feedback.json No dependencies beyond the Python stdlib are required. """ import argparse import base64 import json import mimetypes import os import re import signal import subprocess import sys import time import webbrowser from functools import partial from http.server import HTTPServer, BaseHTTPRequestHandler from pathlib import Path # Files to exclude from output listings METADATA_FILES = {"transcript.md", "user_notes.md", "metrics.json"} # Extensions we render as inline text TEXT_EXTENSIONS = { ".txt", ".md", ".json", ".csv", ".py", ".js", ".ts", ".tsx", ".jsx", ".yaml", ".yml", ".xml", ".html", ".css", ".sh", ".rb", ".go", ".rs", ".java", ".c", ".cpp", ".h", ".hpp", ".sql", ".r", ".toml", } # Extensions we render as inline images IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"} # MIME type overrides for common types MIME_OVERRIDES = { ".svg": "image/svg+xml", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", } def get_mime_type(path: Path) -> str: ext = path.suffix.lower() if ext in MIME_OVERRIDES: return MIME_OVERRIDES[ext] mime, _ = mimetypes.guess_type(str(path)) return mime or "application/octet-stream" def find_runs(workspace: Path) -> list[dict]: """Recursively find directories that contain an outputs/ subdirectory.""" runs: list[dict] = [] _find_runs_recursive(workspace, workspace, runs) runs.sort(key=lambda r: (r.get("eval_id", float("inf")), r["id"])) return runs def _find_runs_recursive(root: Path, current: Path, runs: list[dict]) -> None: if not current.is_dir(): return outputs_dir = current / "outputs" if outputs_dir.is_dir(): run = build_run(root, current) if run: runs.append(run) return skip = {"node_modules", ".git", "__pycache__", "skill", "inputs"} for child in sorted(current.iterdir()): if child.is_dir() and child.name not in skip: _find_runs_recursive(root, child, runs) def build_run(root: Path, run_dir: Path) -> dict | None: """Build a run dict with prompt, outputs, and grading data.""" prompt = "" eval_id = None # Try eval_metadata.json for candidate in [run_dir / "eval_metadata.json", run_dir.parent / "eval_metadata.json"]: if candidate.exists(): try: metadata = json.loads(candidate.read_text()) prompt = metadata.get("prompt", "") eval_id = metadata.get("eval_id") except (json.JSONDecodeError, OSError): pass if prompt: break # Fall back to transcript.md if not prompt: for candidate in [run_dir / "transcript.md", run_dir / "outputs" / "transcript.md"]: if candidate.exists(): try: text = candidate.read_text() match = re.search(r"## Eval Prompt\n\n([\s\S]*?)(?=\n##|$)", text) if match: prompt = match.group(1).strip() except OSError: pass if prompt: break if not prompt: prompt = "(No prompt found)" run_id = str(run_dir.relative_to(root)).replace("/", "-").replace("\\", "-") # Collect output files outputs_dir = run_dir / "outputs" output_files: list[dict] = [] if outputs_dir.is_dir(): for f in sorted(outputs_dir.iterdir()): if f.is_file() and f.name not in METADATA_FILES: output_files.append(embed_file(f)) # Load grading if present grading = None for candidate in [run_dir / "grading.json", run_dir.parent / "grading.json"]: if candidate.exists(): try: grading = json.loads(candidate.read_text()) except (json.JSONDecodeError, OSError): pass if grading: break return { "id": run_id, "prompt": prompt, "eval_id": eval_id, "outputs": output_files, "grading": grading, } def embed_file(path: Path) -> dict: """Read a file and return an embedded representation.""" ext = path.suffix.lower() mime = get_mime_type(path) if ext in TEXT_EXTENSIONS: try: content = path.read_text(errors="replace") except OSError: content = "(Error reading file)" return { "name": path.name, "type": "text", "content": content, } elif ext in IMAGE_EXTENSIONS: try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "image", "mime": mime, "data_uri": f"data:{mime};base64,{b64}", } elif ext == ".pdf": try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "pdf", "data_uri": f"data:{mime};base64,{b64}", } elif ext == ".xlsx": try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "xlsx", "data_b64": b64, } else: # Binary / unknown — base64 download link try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "binary", "mime": mime, "data_uri": f"data:{mime};base64,{b64}", } def load_previous_iteration(workspace: Path) -> dict[str, dict]: """Load previous iteration's feedback and outputs. Returns a map of run_id -> {"feedback": str, "outputs": list[dict]}. """ result: dict[str, dict] = {} # Load feedback feedback_map: dict[str, str] = {} feedback_path = workspace / "feedback.json" if feedback_path.exists(): try: data = json.loads(feedback_path.read_text()) feedback_map = { r["run_id"]: r["feedback"] for r in data.get("reviews", []) if r.get("feedback", "").strip() } except (json.JSONDecodeError, OSError, KeyError): pass # Load runs (to get outputs) prev_runs = find_runs(workspace) for run in prev_runs: result[run["id"]] = { "feedback": feedback_map.get(run["id"], ""), "outputs": run.get("outputs", []), } # Also add feedback for run_ids that had feedback but no matching run for run_id, fb in feedback_map.items(): if run_id not in result: result[run_id] = {"feedback": fb, "outputs": []} return result def generate_html( runs: list[dict], skill_name: str, previous: dict[str, dict] | None = None, benchmark: dict | None = None, ) -> str: """Generate the complete standalone HTML page with embedded data.""" template_path = Path(__file__).parent / "viewer.html" template = template_path.read_text() # Build previous_feedback and previous_outputs maps for the template previous_feedback: dict[str, str] = {} previous_outputs: dict[str, list[dict]] = {} if previous: for run_id, data in previous.items(): if data.get("feedback"): previous_feedback[run_id] = data["feedback"] if data.get("outputs"): previous_outputs[run_id] = data["outputs"] embedded = { "skill_name": skill_name, "runs": runs, "previous_feedback": previous_feedback, "previous_outputs": previous_outputs, } if benchmark: embedded["benchmark"] = benchmark data_json = json.dumps(embedded) return template.replace("/*__EMBEDDED_DATA__*/", f"const EMBEDDED_DATA = {data_json};") # --------------------------------------------------------------------------- # HTTP server (stdlib only, zero dependencies) # --------------------------------------------------------------------------- def _kill_port(port: int) -> None: """Kill any process listening on the given port.""" try: result = subprocess.run( ["lsof", "-ti", f":{port}"], capture_output=True, text=True, timeout=5, ) for pid_str in result.stdout.strip().split("\n"): if pid_str.strip(): try: os.kill(int(pid_str.strip()), signal.SIGTERM) except (ProcessLookupError, ValueError): pass if result.stdout.strip(): time.sleep(0.5) except subprocess.TimeoutExpired: pass except FileNotFoundError: print("Note: lsof not found, cannot check if port is in use", file=sys.stderr) class ReviewHandler(BaseHTTPRequestHandler): """Serves the review HTML and handles feedback saves. Regenerates the HTML on each page load so that refreshing the browser picks up new eval outputs without restarting the server. """ def __init__( self, workspace: Path, skill_name: str, feedback_path: Path, previous: dict[str, dict], benchmark_path: Path | None, *args, **kwargs, ): self.workspace = workspace self.skill_name = skill_name self.feedback_path = feedback_path self.previous = previous self.benchmark_path = benchmark_path super().__init__(*args, **kwargs) def do_GET(self) -> None: if self.path == "/" or self.path == "/index.html": # Regenerate HTML on each request (re-scans workspace for new outputs) runs = find_runs(self.workspace) benchmark = None if self.benchmark_path and self.benchmark_path.exists(): try: benchmark = json.loads(self.benchmark_path.read_text()) except (json.JSONDecodeError, OSError): pass html = generate_html(runs, self.skill_name, self.previous, benchmark) content = html.encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) elif self.path == "/api/feedback": data = b"{}" if self.feedback_path.exists(): data = self.feedback_path.read_bytes() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) else: self.send_error(404) def do_POST(self) -> None: if self.path == "/api/feedback": length = int(self.headers.get("Content-Length", 0)) body = self.rfile.read(length) try: data = json.loads(body) if not isinstance(data, dict) or "reviews" not in data: raise ValueError("Expected JSON object with 'reviews' key") self.feedback_path.write_text(json.dumps(data, indent=2) + "\n") resp = b'{"ok":true}' self.send_response(200) except (json.JSONDecodeError, OSError, ValueError) as e: resp = json.dumps({"error": str(e)}).encode() self.send_response(500) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(resp))) self.end_headers() self.wfile.write(resp) else: self.send_error(404) def log_message(self, format: str, *args: object) -> None: # Suppress request logging to keep terminal clean pass def main() -> None: parser = argparse.ArgumentParser(description="Generate and serve eval review") parser.add_argument("workspace", type=Path, help="Path to workspace directory") parser.add_argument("--port", "-p", type=int, default=3117, help="Server port (default: 3117)") parser.add_argument("--skill-name", "-n", type=str, default=None, help="Skill name for header") parser.add_argument( "--previous-workspace", type=Path, default=None, help="Path to previous iteration's workspace (shows old outputs and feedback as context)", ) parser.add_argument( "--benchmark", type=Path, default=None, help="Path to benchmark.json to show in the Benchmark tab", ) parser.add_argument( "--static", "-s", type=Path, default=None, help="Write standalone HTML to this path instead of starting a server", ) args = parser.parse_args() workspace = args.workspace.resolve() if not workspace.is_dir(): print(f"Error: {workspace} is not a directory", file=sys.stderr) sys.exit(1) runs = find_runs(workspace) if not runs: print(f"No runs found in {workspace}", file=sys.stderr) sys.exit(1) skill_name = args.skill_name or workspace.name.replace("-workspace", "") feedback_path = workspace / "feedback.json" previous: dict[str, dict] = {} if args.previous_workspace: previous = load_previous_iteration(args.previous_workspace.resolve()) benchmark_path = args.benchmark.resolve() if args.benchmark else None benchmark = None if benchmark_path and benchmark_path.exists(): try: benchmark = json.loads(benchmark_path.read_text()) except (json.JSONDecodeError, OSError): pass if args.static: html = generate_html(runs, skill_name, previous, benchmark) args.static.parent.mkdir(parents=True, exist_ok=True) args.static.write_text(html) print(f"\n Static viewer written to: {args.static}\n") sys.exit(0) # Kill any existing process on the target port port = args.port _kill_port(port) handler = partial(ReviewHandler, workspace, skill_name, feedback_path, previous, benchmark_path) try: server = HTTPServer(("127.0.0.1", port), handler) except OSError: # Port still in use after kill attempt — find a free one server = HTTPServer(("127.0.0.1", 0), handler) port = server.server_address[1] url = f"http://localhost:{port}" print(f"\n Eval Viewer") print(f" ─────────────────────────────────") print(f" URL: {url}") print(f" Workspace: {workspace}") print(f" Feedback: {feedback_path}") if previous: print(f" Previous: {args.previous_workspace} ({len(previous)} runs)") if benchmark_path: print(f" Benchmark: {benchmark_path}") print(f"\n Press Ctrl+C to stop.\n") webbrowser.open(url) try: server.serve_forever() except KeyboardInterrupt: print("\nStopped.") server.server_close() if __name__ == "__main__": main() ================================================ FILE: .claude/skills/skill-creator/eval-viewer/viewer.html ================================================ Eval Review

Eval Review:

Review each output and leave feedback below. Navigate with arrow keys or buttons. When done, copy feedback and paste into Claude Code.
Prompt
Output
No output files found
Your Feedback
No benchmark data available. Run a benchmark to see quantitative results here.

Review Complete

Your feedback has been saved. Go back to your Claude Code session and tell Claude you're done reviewing.

================================================ FILE: .claude/skills/skill-creator/references/schemas.md ================================================ # JSON Schemas This document defines the JSON schemas used by skill-creator. --- ## evals.json Defines the evals for a skill. Located at `evals/evals.json` within the skill directory. ```json { "skill_name": "example-skill", "evals": [ { "id": 1, "prompt": "User's example prompt", "expected_output": "Description of expected result", "files": ["evals/files/sample1.pdf"], "expectations": [ "The output includes X", "The skill used script Y" ] } ] } ``` **Fields:** - `skill_name`: Name matching the skill's frontmatter - `evals[].id`: Unique integer identifier - `evals[].prompt`: The task to execute - `evals[].expected_output`: Human-readable description of success - `evals[].files`: Optional list of input file paths (relative to skill root) - `evals[].expectations`: List of verifiable statements --- ## history.json Tracks version progression in Improve mode. Located at workspace root. ```json { "started_at": "2026-01-15T10:30:00Z", "skill_name": "pdf", "current_best": "v2", "iterations": [ { "version": "v0", "parent": null, "expectation_pass_rate": 0.65, "grading_result": "baseline", "is_current_best": false }, { "version": "v1", "parent": "v0", "expectation_pass_rate": 0.75, "grading_result": "won", "is_current_best": false }, { "version": "v2", "parent": "v1", "expectation_pass_rate": 0.85, "grading_result": "won", "is_current_best": true } ] } ``` **Fields:** - `started_at`: ISO timestamp of when improvement started - `skill_name`: Name of the skill being improved - `current_best`: Version identifier of the best performer - `iterations[].version`: Version identifier (v0, v1, ...) - `iterations[].parent`: Parent version this was derived from - `iterations[].expectation_pass_rate`: Pass rate from grading - `iterations[].grading_result`: "baseline", "won", "lost", or "tie" - `iterations[].is_current_best`: Whether this is the current best version --- ## grading.json Output from the grader agent. Located at `/grading.json`. ```json { "expectations": [ { "text": "The output includes the name 'John Smith'", "passed": true, "evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'" }, { "text": "The spreadsheet has a SUM formula in cell B10", "passed": false, "evidence": "No spreadsheet was created. The output was a text file." } ], "summary": { "passed": 2, "failed": 1, "total": 3, "pass_rate": 0.67 }, "execution_metrics": { "tool_calls": { "Read": 5, "Write": 2, "Bash": 8 }, "total_tool_calls": 15, "total_steps": 6, "errors_encountered": 0, "output_chars": 12450, "transcript_chars": 3200 }, "timing": { "executor_duration_seconds": 165.0, "grader_duration_seconds": 26.0, "total_duration_seconds": 191.0 }, "claims": [ { "claim": "The form has 12 fillable fields", "type": "factual", "verified": true, "evidence": "Counted 12 fields in field_info.json" } ], "user_notes_summary": { "uncertainties": ["Used 2023 data, may be stale"], "needs_review": [], "workarounds": ["Fell back to text overlay for non-fillable fields"] }, "eval_feedback": { "suggestions": [ { "assertion": "The output includes the name 'John Smith'", "reason": "A hallucinated document that mentions the name would also pass" } ], "overall": "Assertions check presence but not correctness." } } ``` **Fields:** - `expectations[]`: Graded expectations with evidence - `summary`: Aggregate pass/fail counts - `execution_metrics`: Tool usage and output size (from executor's metrics.json) - `timing`: Wall clock timing (from timing.json) - `claims`: Extracted and verified claims from the output - `user_notes_summary`: Issues flagged by the executor - `eval_feedback`: (optional) Improvement suggestions for the evals, only present when the grader identifies issues worth raising --- ## metrics.json Output from the executor agent. Located at `/outputs/metrics.json`. ```json { "tool_calls": { "Read": 5, "Write": 2, "Bash": 8, "Edit": 1, "Glob": 2, "Grep": 0 }, "total_tool_calls": 18, "total_steps": 6, "files_created": ["filled_form.pdf", "field_values.json"], "errors_encountered": 0, "output_chars": 12450, "transcript_chars": 3200 } ``` **Fields:** - `tool_calls`: Count per tool type - `total_tool_calls`: Sum of all tool calls - `total_steps`: Number of major execution steps - `files_created`: List of output files created - `errors_encountered`: Number of errors during execution - `output_chars`: Total character count of output files - `transcript_chars`: Character count of transcript --- ## timing.json Wall clock timing for a run. Located at `/timing.json`. **How to capture:** When a subagent task completes, the task notification includes `total_tokens` and `duration_ms`. Save these immediately — they are not persisted anywhere else and cannot be recovered after the fact. ```json { "total_tokens": 84852, "duration_ms": 23332, "total_duration_seconds": 23.3, "executor_start": "2026-01-15T10:30:00Z", "executor_end": "2026-01-15T10:32:45Z", "executor_duration_seconds": 165.0, "grader_start": "2026-01-15T10:32:46Z", "grader_end": "2026-01-15T10:33:12Z", "grader_duration_seconds": 26.0 } ``` --- ## benchmark.json Output from Benchmark mode. Located at `benchmarks//benchmark.json`. ```json { "metadata": { "skill_name": "pdf", "skill_path": "/path/to/pdf", "executor_model": "claude-sonnet-4-20250514", "analyzer_model": "most-capable-model", "timestamp": "2026-01-15T10:30:00Z", "evals_run": [1, 2, 3], "runs_per_configuration": 3 }, "runs": [ { "eval_id": 1, "eval_name": "Ocean", "configuration": "with_skill", "run_number": 1, "result": { "pass_rate": 0.85, "passed": 6, "failed": 1, "total": 7, "time_seconds": 42.5, "tokens": 3800, "tool_calls": 18, "errors": 0 }, "expectations": [ {"text": "...", "passed": true, "evidence": "..."} ], "notes": [ "Used 2023 data, may be stale", "Fell back to text overlay for non-fillable fields" ] } ], "run_summary": { "with_skill": { "pass_rate": {"mean": 0.85, "stddev": 0.05, "min": 0.80, "max": 0.90}, "time_seconds": {"mean": 45.0, "stddev": 12.0, "min": 32.0, "max": 58.0}, "tokens": {"mean": 3800, "stddev": 400, "min": 3200, "max": 4100} }, "without_skill": { "pass_rate": {"mean": 0.35, "stddev": 0.08, "min": 0.28, "max": 0.45}, "time_seconds": {"mean": 32.0, "stddev": 8.0, "min": 24.0, "max": 42.0}, "tokens": {"mean": 2100, "stddev": 300, "min": 1800, "max": 2500} }, "delta": { "pass_rate": "+0.50", "time_seconds": "+13.0", "tokens": "+1700" } }, "notes": [ "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value", "Eval 3 shows high variance (50% ± 40%) - may be flaky or model-dependent", "Without-skill runs consistently fail on table extraction expectations", "Skill adds 13s average execution time but improves pass rate by 50%" ] } ``` **Fields:** - `metadata`: Information about the benchmark run - `skill_name`: Name of the skill - `timestamp`: When the benchmark was run - `evals_run`: List of eval names or IDs - `runs_per_configuration`: Number of runs per config (e.g. 3) - `runs[]`: Individual run results - `eval_id`: Numeric eval identifier - `eval_name`: Human-readable eval name (used as section header in the viewer) - `configuration`: Must be `"with_skill"` or `"without_skill"` (the viewer uses this exact string for grouping and color coding) - `run_number`: Integer run number (1, 2, 3...) - `result`: Nested object with `pass_rate`, `passed`, `total`, `time_seconds`, `tokens`, `errors` - `run_summary`: Statistical aggregates per configuration - `with_skill` / `without_skill`: Each contains `pass_rate`, `time_seconds`, `tokens` objects with `mean` and `stddev` fields - `delta`: Difference strings like `"+0.50"`, `"+13.0"`, `"+1700"` - `notes`: Freeform observations from the analyzer **Important:** The viewer reads these field names exactly. Using `config` instead of `configuration`, or putting `pass_rate` at the top level of a run instead of nested under `result`, will cause the viewer to show empty/zero values. Always reference this schema when generating benchmark.json manually. --- ## comparison.json Output from blind comparator. Located at `/comparison-N.json`. ```json { "winner": "A", "reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.", "rubric": { "A": { "content": { "correctness": 5, "completeness": 5, "accuracy": 4 }, "structure": { "organization": 4, "formatting": 5, "usability": 4 }, "content_score": 4.7, "structure_score": 4.3, "overall_score": 9.0 }, "B": { "content": { "correctness": 3, "completeness": 2, "accuracy": 3 }, "structure": { "organization": 3, "formatting": 2, "usability": 3 }, "content_score": 2.7, "structure_score": 2.7, "overall_score": 5.4 } }, "output_quality": { "A": { "score": 9, "strengths": ["Complete solution", "Well-formatted", "All fields present"], "weaknesses": ["Minor style inconsistency in header"] }, "B": { "score": 5, "strengths": ["Readable output", "Correct basic structure"], "weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"] } }, "expectation_results": { "A": { "passed": 4, "total": 5, "pass_rate": 0.80, "details": [ {"text": "Output includes name", "passed": true} ] }, "B": { "passed": 3, "total": 5, "pass_rate": 0.60, "details": [ {"text": "Output includes name", "passed": true} ] } } } ``` --- ## analysis.json Output from post-hoc analyzer. Located at `/analysis.json`. ```json { "comparison_summary": { "winner": "A", "winner_skill": "path/to/winner/skill", "loser_skill": "path/to/loser/skill", "comparator_reasoning": "Brief summary of why comparator chose winner" }, "winner_strengths": [ "Clear step-by-step instructions for handling multi-page documents", "Included validation script that caught formatting errors" ], "loser_weaknesses": [ "Vague instruction 'process the document appropriately' led to inconsistent behavior", "No script for validation, agent had to improvise" ], "instruction_following": { "winner": { "score": 9, "issues": ["Minor: skipped optional logging step"] }, "loser": { "score": 6, "issues": [ "Did not use the skill's formatting template", "Invented own approach instead of following step 3" ] } }, "improvement_suggestions": [ { "priority": "high", "category": "instructions", "suggestion": "Replace 'process the document appropriately' with explicit steps", "expected_impact": "Would eliminate ambiguity that caused inconsistent behavior" } ], "transcript_insights": { "winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script", "loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods" } } ``` ================================================ FILE: .claude/skills/skill-creator/scripts/aggregate_benchmark.py ================================================ #!/usr/bin/env python3 """ Aggregate individual run results into benchmark summary statistics. Reads grading.json files from run directories and produces: - run_summary with mean, stddev, min, max for each metric - delta between with_skill and without_skill configurations Usage: python aggregate_benchmark.py Example: python aggregate_benchmark.py benchmarks/2026-01-15T10-30-00/ The script supports two directory layouts: Workspace layout (from skill-creator iterations): / └── eval-N/ ├── with_skill/ │ ├── run-1/grading.json │ └── run-2/grading.json └── without_skill/ ├── run-1/grading.json └── run-2/grading.json Legacy layout (with runs/ subdirectory): / └── runs/ └── eval-N/ ├── with_skill/ │ └── run-1/grading.json └── without_skill/ └── run-1/grading.json """ import argparse import json import math import sys from datetime import datetime, timezone from pathlib import Path def calculate_stats(values: list[float]) -> dict: """Calculate mean, stddev, min, max for a list of values.""" if not values: return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0} n = len(values) mean = sum(values) / n if n > 1: variance = sum((x - mean) ** 2 for x in values) / (n - 1) stddev = math.sqrt(variance) else: stddev = 0.0 return { "mean": round(mean, 4), "stddev": round(stddev, 4), "min": round(min(values), 4), "max": round(max(values), 4) } def load_run_results(benchmark_dir: Path) -> dict: """ Load all run results from a benchmark directory. Returns dict keyed by config name (e.g. "with_skill"/"without_skill", or "new_skill"/"old_skill"), each containing a list of run results. """ # Support both layouts: eval dirs directly under benchmark_dir, or under runs/ runs_dir = benchmark_dir / "runs" if runs_dir.exists(): search_dir = runs_dir elif list(benchmark_dir.glob("eval-*")): search_dir = benchmark_dir else: print(f"No eval directories found in {benchmark_dir} or {benchmark_dir / 'runs'}") return {} results: dict[str, list] = {} for eval_idx, eval_dir in enumerate(sorted(search_dir.glob("eval-*"))): metadata_path = eval_dir / "eval_metadata.json" if metadata_path.exists(): try: with open(metadata_path) as mf: eval_id = json.load(mf).get("eval_id", eval_idx) except (json.JSONDecodeError, OSError): eval_id = eval_idx else: try: eval_id = int(eval_dir.name.split("-")[1]) except ValueError: eval_id = eval_idx # Discover config directories dynamically rather than hardcoding names for config_dir in sorted(eval_dir.iterdir()): if not config_dir.is_dir(): continue # Skip non-config directories (inputs, outputs, etc.) if not list(config_dir.glob("run-*")): continue config = config_dir.name if config not in results: results[config] = [] for run_dir in sorted(config_dir.glob("run-*")): run_number = int(run_dir.name.split("-")[1]) grading_file = run_dir / "grading.json" if not grading_file.exists(): print(f"Warning: grading.json not found in {run_dir}") continue try: with open(grading_file) as f: grading = json.load(f) except json.JSONDecodeError as e: print(f"Warning: Invalid JSON in {grading_file}: {e}") continue # Extract metrics result = { "eval_id": eval_id, "run_number": run_number, "pass_rate": grading.get("summary", {}).get("pass_rate", 0.0), "passed": grading.get("summary", {}).get("passed", 0), "failed": grading.get("summary", {}).get("failed", 0), "total": grading.get("summary", {}).get("total", 0), } # Extract timing — check grading.json first, then sibling timing.json timing = grading.get("timing", {}) result["time_seconds"] = timing.get("total_duration_seconds", 0.0) timing_file = run_dir / "timing.json" if result["time_seconds"] == 0.0 and timing_file.exists(): try: with open(timing_file) as tf: timing_data = json.load(tf) result["time_seconds"] = timing_data.get("total_duration_seconds", 0.0) result["tokens"] = timing_data.get("total_tokens", 0) except json.JSONDecodeError: pass # Extract metrics if available metrics = grading.get("execution_metrics", {}) result["tool_calls"] = metrics.get("total_tool_calls", 0) if not result.get("tokens"): result["tokens"] = metrics.get("output_chars", 0) result["errors"] = metrics.get("errors_encountered", 0) # Extract expectations — viewer requires fields: text, passed, evidence raw_expectations = grading.get("expectations", []) for exp in raw_expectations: if "text" not in exp or "passed" not in exp: print(f"Warning: expectation in {grading_file} missing required fields (text, passed, evidence): {exp}") result["expectations"] = raw_expectations # Extract notes from user_notes_summary notes_summary = grading.get("user_notes_summary", {}) notes = [] notes.extend(notes_summary.get("uncertainties", [])) notes.extend(notes_summary.get("needs_review", [])) notes.extend(notes_summary.get("workarounds", [])) result["notes"] = notes results[config].append(result) return results def aggregate_results(results: dict) -> dict: """ Aggregate run results into summary statistics. Returns run_summary with stats for each configuration and delta. """ run_summary = {} configs = list(results.keys()) for config in configs: runs = results.get(config, []) if not runs: run_summary[config] = { "pass_rate": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}, "time_seconds": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}, "tokens": {"mean": 0, "stddev": 0, "min": 0, "max": 0} } continue pass_rates = [r["pass_rate"] for r in runs] times = [r["time_seconds"] for r in runs] tokens = [r.get("tokens", 0) for r in runs] run_summary[config] = { "pass_rate": calculate_stats(pass_rates), "time_seconds": calculate_stats(times), "tokens": calculate_stats(tokens) } # Calculate delta between the first two configs (if two exist) if len(configs) >= 2: primary = run_summary.get(configs[0], {}) baseline = run_summary.get(configs[1], {}) else: primary = run_summary.get(configs[0], {}) if configs else {} baseline = {} delta_pass_rate = primary.get("pass_rate", {}).get("mean", 0) - baseline.get("pass_rate", {}).get("mean", 0) delta_time = primary.get("time_seconds", {}).get("mean", 0) - baseline.get("time_seconds", {}).get("mean", 0) delta_tokens = primary.get("tokens", {}).get("mean", 0) - baseline.get("tokens", {}).get("mean", 0) run_summary["delta"] = { "pass_rate": f"{delta_pass_rate:+.2f}", "time_seconds": f"{delta_time:+.1f}", "tokens": f"{delta_tokens:+.0f}" } return run_summary def generate_benchmark(benchmark_dir: Path, skill_name: str = "", skill_path: str = "") -> dict: """ Generate complete benchmark.json from run results. """ results = load_run_results(benchmark_dir) run_summary = aggregate_results(results) # Build runs array for benchmark.json runs = [] for config in results: for result in results[config]: runs.append({ "eval_id": result["eval_id"], "configuration": config, "run_number": result["run_number"], "result": { "pass_rate": result["pass_rate"], "passed": result["passed"], "failed": result["failed"], "total": result["total"], "time_seconds": result["time_seconds"], "tokens": result.get("tokens", 0), "tool_calls": result.get("tool_calls", 0), "errors": result.get("errors", 0) }, "expectations": result["expectations"], "notes": result["notes"] }) # Determine eval IDs from results eval_ids = sorted(set( r["eval_id"] for config in results.values() for r in config )) benchmark = { "metadata": { "skill_name": skill_name or "", "skill_path": skill_path or "", "executor_model": "", "analyzer_model": "", "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "evals_run": eval_ids, "runs_per_configuration": 3 }, "runs": runs, "run_summary": run_summary, "notes": [] # To be filled by analyzer } return benchmark def generate_markdown(benchmark: dict) -> str: """Generate human-readable benchmark.md from benchmark data.""" metadata = benchmark["metadata"] run_summary = benchmark["run_summary"] # Determine config names (excluding "delta") configs = [k for k in run_summary if k != "delta"] config_a = configs[0] if len(configs) >= 1 else "config_a" config_b = configs[1] if len(configs) >= 2 else "config_b" label_a = config_a.replace("_", " ").title() label_b = config_b.replace("_", " ").title() lines = [ f"# Skill Benchmark: {metadata['skill_name']}", "", f"**Model**: {metadata['executor_model']}", f"**Date**: {metadata['timestamp']}", f"**Evals**: {', '.join(map(str, metadata['evals_run']))} ({metadata['runs_per_configuration']} runs each per configuration)", "", "## Summary", "", f"| Metric | {label_a} | {label_b} | Delta |", "|--------|------------|---------------|-------|", ] a_summary = run_summary.get(config_a, {}) b_summary = run_summary.get(config_b, {}) delta = run_summary.get("delta", {}) # Format pass rate a_pr = a_summary.get("pass_rate", {}) b_pr = b_summary.get("pass_rate", {}) lines.append(f"| Pass Rate | {a_pr.get('mean', 0)*100:.0f}% ± {a_pr.get('stddev', 0)*100:.0f}% | {b_pr.get('mean', 0)*100:.0f}% ± {b_pr.get('stddev', 0)*100:.0f}% | {delta.get('pass_rate', '—')} |") # Format time a_time = a_summary.get("time_seconds", {}) b_time = b_summary.get("time_seconds", {}) lines.append(f"| Time | {a_time.get('mean', 0):.1f}s ± {a_time.get('stddev', 0):.1f}s | {b_time.get('mean', 0):.1f}s ± {b_time.get('stddev', 0):.1f}s | {delta.get('time_seconds', '—')}s |") # Format tokens a_tokens = a_summary.get("tokens", {}) b_tokens = b_summary.get("tokens", {}) lines.append(f"| Tokens | {a_tokens.get('mean', 0):.0f} ± {a_tokens.get('stddev', 0):.0f} | {b_tokens.get('mean', 0):.0f} ± {b_tokens.get('stddev', 0):.0f} | {delta.get('tokens', '—')} |") # Notes section if benchmark.get("notes"): lines.extend([ "", "## Notes", "" ]) for note in benchmark["notes"]: lines.append(f"- {note}") return "\n".join(lines) def main(): parser = argparse.ArgumentParser( description="Aggregate benchmark run results into summary statistics" ) parser.add_argument( "benchmark_dir", type=Path, help="Path to the benchmark directory" ) parser.add_argument( "--skill-name", default="", help="Name of the skill being benchmarked" ) parser.add_argument( "--skill-path", default="", help="Path to the skill being benchmarked" ) parser.add_argument( "--output", "-o", type=Path, help="Output path for benchmark.json (default: /benchmark.json)" ) args = parser.parse_args() if not args.benchmark_dir.exists(): print(f"Directory not found: {args.benchmark_dir}") sys.exit(1) # Generate benchmark benchmark = generate_benchmark(args.benchmark_dir, args.skill_name, args.skill_path) # Determine output paths output_json = args.output or (args.benchmark_dir / "benchmark.json") output_md = output_json.with_suffix(".md") # Write benchmark.json with open(output_json, "w") as f: json.dump(benchmark, f, indent=2) print(f"Generated: {output_json}") # Write benchmark.md markdown = generate_markdown(benchmark) with open(output_md, "w") as f: f.write(markdown) print(f"Generated: {output_md}") # Print summary run_summary = benchmark["run_summary"] configs = [k for k in run_summary if k != "delta"] delta = run_summary.get("delta", {}) print(f"\nSummary:") for config in configs: pr = run_summary[config]["pass_rate"]["mean"] label = config.replace("_", " ").title() print(f" {label}: {pr*100:.1f}% pass rate") print(f" Delta: {delta.get('pass_rate', '—')}") if __name__ == "__main__": main() ================================================ FILE: .claude/skills/skill-creator/scripts/generate_report.py ================================================ #!/usr/bin/env python3 """Generate an HTML report from run_loop.py output. Takes the JSON output from run_loop.py and generates a visual HTML report showing each description attempt with check/x for each test case. Distinguishes between train and test queries. """ import argparse import html import json import sys from pathlib import Path def generate_html(data: dict, auto_refresh: bool = False, skill_name: str = "") -> str: """Generate HTML report from loop output data. If auto_refresh is True, adds a meta refresh tag.""" history = data.get("history", []) holdout = data.get("holdout", 0) title_prefix = html.escape(skill_name + " \u2014 ") if skill_name else "" # Get all unique queries from train and test sets, with should_trigger info train_queries: list[dict] = [] test_queries: list[dict] = [] if history: for r in history[0].get("train_results", history[0].get("results", [])): train_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)}) if history[0].get("test_results"): for r in history[0].get("test_results", []): test_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)}) refresh_tag = ' \n' if auto_refresh else "" html_parts = [""" """ + refresh_tag + """ """ + title_prefix + """Skill Description Optimization

""" + title_prefix + """Skill Description Optimization

Optimizing your skill's description. This page updates automatically as Claude tests different versions of your skill's description. Each row is an iteration — a new description attempt. The columns show test queries: green checkmarks mean the skill triggered correctly (or correctly didn't trigger), red crosses mean it got it wrong. The "Train" score shows performance on queries used to improve the description; the "Test" score shows performance on held-out queries the optimizer hasn't seen. When it's done, Claude will apply the best-performing description to your skill.
"""] # Summary section best_test_score = data.get('best_test_score') best_train_score = data.get('best_train_score') html_parts.append(f"""

Original: {html.escape(data.get('original_description', 'N/A'))}

Best: {html.escape(data.get('best_description', 'N/A'))}

Best Score: {data.get('best_score', 'N/A')} {'(test)' if best_test_score else '(train)'}

Iterations: {data.get('iterations_run', 0)} | Train: {data.get('train_size', '?')} | Test: {data.get('test_size', '?')}

""") # Legend html_parts.append("""
Query columns: Should trigger Should NOT trigger Train Test
""") # Table header html_parts.append("""
""") # Add column headers for train queries for qinfo in train_queries: polarity = "positive-col" if qinfo["should_trigger"] else "negative-col" html_parts.append(f' \n') # Add column headers for test queries (different color) for qinfo in test_queries: polarity = "positive-col" if qinfo["should_trigger"] else "negative-col" html_parts.append(f' \n') html_parts.append(""" """) # Find best iteration for highlighting if test_queries: best_iter = max(history, key=lambda h: h.get("test_passed") or 0).get("iteration") else: best_iter = max(history, key=lambda h: h.get("train_passed", h.get("passed", 0))).get("iteration") # Add rows for each iteration for h in history: iteration = h.get("iteration", "?") train_passed = h.get("train_passed", h.get("passed", 0)) train_total = h.get("train_total", h.get("total", 0)) test_passed = h.get("test_passed") test_total = h.get("test_total") description = h.get("description", "") train_results = h.get("train_results", h.get("results", [])) test_results = h.get("test_results", []) # Create lookups for results by query train_by_query = {r["query"]: r for r in train_results} test_by_query = {r["query"]: r for r in test_results} if test_results else {} # Compute aggregate correct/total runs across all retries def aggregate_runs(results: list[dict]) -> tuple[int, int]: correct = 0 total = 0 for r in results: runs = r.get("runs", 0) triggers = r.get("triggers", 0) total += runs if r.get("should_trigger", True): correct += triggers else: correct += runs - triggers return correct, total train_correct, train_runs = aggregate_runs(train_results) test_correct, test_runs = aggregate_runs(test_results) # Determine score classes def score_class(correct: int, total: int) -> str: if total > 0: ratio = correct / total if ratio >= 0.8: return "score-good" elif ratio >= 0.5: return "score-ok" return "score-bad" train_class = score_class(train_correct, train_runs) test_class = score_class(test_correct, test_runs) row_class = "best-row" if iteration == best_iter else "" html_parts.append(f""" """) # Add result for each train query for qinfo in train_queries: r = train_by_query.get(qinfo["query"], {}) did_pass = r.get("pass", False) triggers = r.get("triggers", 0) runs = r.get("runs", 0) icon = "✓" if did_pass else "✗" css_class = "pass" if did_pass else "fail" html_parts.append(f' \n') # Add result for each test query (with different background) for qinfo in test_queries: r = test_by_query.get(qinfo["query"], {}) did_pass = r.get("pass", False) triggers = r.get("triggers", 0) runs = r.get("runs", 0) icon = "✓" if did_pass else "✗" css_class = "pass" if did_pass else "fail" html_parts.append(f' \n') html_parts.append(" \n") html_parts.append("""
Iter Train Test Description{html.escape(qinfo["query"])}{html.escape(qinfo["query"])}
{iteration} {train_correct}/{train_runs} {test_correct}/{test_runs} {html.escape(description)}{icon}{triggers}/{runs}{icon}{triggers}/{runs}
""") html_parts.append(""" """) return "".join(html_parts) def main(): parser = argparse.ArgumentParser(description="Generate HTML report from run_loop output") parser.add_argument("input", help="Path to JSON output from run_loop.py (or - for stdin)") parser.add_argument("-o", "--output", default=None, help="Output HTML file (default: stdout)") parser.add_argument("--skill-name", default="", help="Skill name to include in the report title") args = parser.parse_args() if args.input == "-": data = json.load(sys.stdin) else: data = json.loads(Path(args.input).read_text()) html_output = generate_html(data, skill_name=args.skill_name) if args.output: Path(args.output).write_text(html_output) print(f"Report written to {args.output}", file=sys.stderr) else: print(html_output) if __name__ == "__main__": main() ================================================ FILE: .claude/skills/skill-creator/scripts/improve_description.py ================================================ #!/usr/bin/env python3 """Improve a skill description based on eval results. Takes eval results (from run_eval.py) and generates an improved description using Claude with extended thinking. """ import argparse import json import re import sys from pathlib import Path import anthropic from scripts.utils import parse_skill_md def improve_description( client: anthropic.Anthropic, skill_name: str, skill_content: str, current_description: str, eval_results: dict, history: list[dict], model: str, test_results: dict | None = None, log_dir: Path | None = None, iteration: int | None = None, ) -> str: """Call Claude to improve the description based on eval results.""" failed_triggers = [ r for r in eval_results["results"] if r["should_trigger"] and not r["pass"] ] false_triggers = [ r for r in eval_results["results"] if not r["should_trigger"] and not r["pass"] ] # Build scores summary train_score = f"{eval_results['summary']['passed']}/{eval_results['summary']['total']}" if test_results: test_score = f"{test_results['summary']['passed']}/{test_results['summary']['total']}" scores_summary = f"Train: {train_score}, Test: {test_score}" else: scores_summary = f"Train: {train_score}" prompt = f"""You are optimizing a skill description for a Claude Code skill called "{skill_name}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples. The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones. Here's the current description: "{current_description}" Current scores ({scores_summary}): """ if failed_triggers: prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n" for r in failed_triggers: prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n' prompt += "\n" if false_triggers: prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n" for r in false_triggers: prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n' prompt += "\n" if history: prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n" for h in history: train_s = f"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}" test_s = f"{h.get('test_passed', '?')}/{h.get('test_total', '?')}" if h.get('test_passed') is not None else None score_str = f"train={train_s}" + (f", test={test_s}" if test_s else "") prompt += f'\n' prompt += f'Description: "{h["description"]}"\n' if "results" in h: prompt += "Train results:\n" for r in h["results"]: status = "PASS" if r["pass"] else "FAIL" prompt += f' [{status}] "{r["query"][:80]}" (triggered {r["triggers"]}/{r["runs"]})\n' if h.get("note"): prompt += f'Note: {h["note"]}\n' prompt += "\n\n" prompt += f""" Skill content (for context on what the skill does): {skill_content} Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold: 1. Avoid overfitting 2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description. Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. Here are some tips that we've found to work well in writing these descriptions: - The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does" - The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works. - The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable. - If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings. I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end. Please respond with only the new description text in tags, nothing else.""" response = client.messages.create( model=model, max_tokens=16000, thinking={ "type": "enabled", "budget_tokens": 10000, }, messages=[{"role": "user", "content": prompt}], ) # Extract thinking and text from response thinking_text = "" text = "" for block in response.content: if block.type == "thinking": thinking_text = block.thinking elif block.type == "text": text = block.text # Parse out the tags match = re.search(r"(.*?)", text, re.DOTALL) description = match.group(1).strip().strip('"') if match else text.strip().strip('"') # Log the transcript transcript: dict = { "iteration": iteration, "prompt": prompt, "thinking": thinking_text, "response": text, "parsed_description": description, "char_count": len(description), "over_limit": len(description) > 1024, } # If over 1024 chars, ask the model to shorten it if len(description) > 1024: shorten_prompt = f"Your description is {len(description)} characters, which exceeds the hard 1024 character limit. Please rewrite it to be under 1024 characters while preserving the most important trigger words and intent coverage. Respond with only the new description in tags." shorten_response = client.messages.create( model=model, max_tokens=16000, thinking={ "type": "enabled", "budget_tokens": 10000, }, messages=[ {"role": "user", "content": prompt}, {"role": "assistant", "content": text}, {"role": "user", "content": shorten_prompt}, ], ) shorten_thinking = "" shorten_text = "" for block in shorten_response.content: if block.type == "thinking": shorten_thinking = block.thinking elif block.type == "text": shorten_text = block.text match = re.search(r"(.*?)", shorten_text, re.DOTALL) shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"') transcript["rewrite_prompt"] = shorten_prompt transcript["rewrite_thinking"] = shorten_thinking transcript["rewrite_response"] = shorten_text transcript["rewrite_description"] = shortened transcript["rewrite_char_count"] = len(shortened) description = shortened transcript["final_description"] = description if log_dir: log_dir.mkdir(parents=True, exist_ok=True) log_file = log_dir / f"improve_iter_{iteration or 'unknown'}.json" log_file.write_text(json.dumps(transcript, indent=2)) return description def main(): parser = argparse.ArgumentParser(description="Improve a skill description based on eval results") parser.add_argument("--eval-results", required=True, help="Path to eval results JSON (from run_eval.py)") parser.add_argument("--skill-path", required=True, help="Path to skill directory") parser.add_argument("--history", default=None, help="Path to history JSON (previous attempts)") parser.add_argument("--model", required=True, help="Model for improvement") parser.add_argument("--verbose", action="store_true", help="Print thinking to stderr") args = parser.parse_args() skill_path = Path(args.skill_path) if not (skill_path / "SKILL.md").exists(): print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) sys.exit(1) eval_results = json.loads(Path(args.eval_results).read_text()) history = [] if args.history: history = json.loads(Path(args.history).read_text()) name, _, content = parse_skill_md(skill_path) current_description = eval_results["description"] if args.verbose: print(f"Current: {current_description}", file=sys.stderr) print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr) client = anthropic.Anthropic() new_description = improve_description( client=client, skill_name=name, skill_content=content, current_description=current_description, eval_results=eval_results, history=history, model=args.model, ) if args.verbose: print(f"Improved: {new_description}", file=sys.stderr) # Output as JSON with both the new description and updated history output = { "description": new_description, "history": history + [{ "description": current_description, "passed": eval_results["summary"]["passed"], "failed": eval_results["summary"]["failed"], "total": eval_results["summary"]["total"], "results": eval_results["results"], }], } print(json.dumps(output, indent=2)) if __name__ == "__main__": main() ================================================ FILE: .claude/skills/skill-creator/scripts/package_skill.py ================================================ #!/usr/bin/env python3 """ Skill Packager - Creates a distributable .skill file of a skill folder Usage: python utils/package_skill.py [output-directory] Example: python utils/package_skill.py skills/public/my-skill python utils/package_skill.py skills/public/my-skill ./dist """ import fnmatch import sys import zipfile from pathlib import Path from scripts.quick_validate import validate_skill # Patterns to exclude when packaging skills. EXCLUDE_DIRS = {"__pycache__", "node_modules"} EXCLUDE_GLOBS = {"*.pyc"} EXCLUDE_FILES = {".DS_Store"} # Directories excluded only at the skill root (not when nested deeper). ROOT_EXCLUDE_DIRS = {"evals"} def should_exclude(rel_path: Path) -> bool: """Check if a path should be excluded from packaging.""" parts = rel_path.parts if any(part in EXCLUDE_DIRS for part in parts): return True # rel_path is relative to skill_path.parent, so parts[0] is the skill # folder name and parts[1] (if present) is the first subdir. if len(parts) > 1 and parts[1] in ROOT_EXCLUDE_DIRS: return True name = rel_path.name if name in EXCLUDE_FILES: return True return any(fnmatch.fnmatch(name, pat) for pat in EXCLUDE_GLOBS) def package_skill(skill_path, output_dir=None): """ Package a skill folder into a .skill file. Args: skill_path: Path to the skill folder output_dir: Optional output directory for the .skill file (defaults to current directory) Returns: Path to the created .skill file, or None if error """ skill_path = Path(skill_path).resolve() # Validate skill folder exists if not skill_path.exists(): print(f"❌ Error: Skill folder not found: {skill_path}") return None if not skill_path.is_dir(): print(f"❌ Error: Path is not a directory: {skill_path}") return None # Validate SKILL.md exists skill_md = skill_path / "SKILL.md" if not skill_md.exists(): print(f"❌ Error: SKILL.md not found in {skill_path}") return None # Run validation before packaging print("🔍 Validating skill...") valid, message = validate_skill(skill_path) if not valid: print(f"❌ Validation failed: {message}") print(" Please fix the validation errors before packaging.") return None print(f"✅ {message}\n") # Determine output location skill_name = skill_path.name if output_dir: output_path = Path(output_dir).resolve() output_path.mkdir(parents=True, exist_ok=True) else: output_path = Path.cwd() skill_filename = output_path / f"{skill_name}.skill" # Create the .skill file (zip format) try: with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf: # Walk through the skill directory, excluding build artifacts for file_path in skill_path.rglob('*'): if not file_path.is_file(): continue arcname = file_path.relative_to(skill_path.parent) if should_exclude(arcname): print(f" Skipped: {arcname}") continue zipf.write(file_path, arcname) print(f" Added: {arcname}") print(f"\n✅ Successfully packaged skill to: {skill_filename}") return skill_filename except Exception as e: print(f"❌ Error creating .skill file: {e}") return None def main(): if len(sys.argv) < 2: print("Usage: python utils/package_skill.py [output-directory]") print("\nExample:") print(" python utils/package_skill.py skills/public/my-skill") print(" python utils/package_skill.py skills/public/my-skill ./dist") sys.exit(1) skill_path = sys.argv[1] output_dir = sys.argv[2] if len(sys.argv) > 2 else None print(f"📦 Packaging skill: {skill_path}") if output_dir: print(f" Output directory: {output_dir}") print() result = package_skill(skill_path, output_dir) if result: sys.exit(0) else: sys.exit(1) if __name__ == "__main__": main() ================================================ FILE: .claude/skills/skill-creator/scripts/quick_validate.py ================================================ #!/usr/bin/env python3 """ Quick validation script for skills - minimal version """ import sys import os import re import yaml from pathlib import Path def validate_skill(skill_path): """Basic validation of a skill""" skill_path = Path(skill_path) # Check SKILL.md exists skill_md = skill_path / 'SKILL.md' if not skill_md.exists(): return False, "SKILL.md not found" # Read and validate frontmatter content = skill_md.read_text() if not content.startswith('---'): return False, "No YAML frontmatter found" # Extract frontmatter match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL) if not match: return False, "Invalid frontmatter format" frontmatter_text = match.group(1) # Parse YAML frontmatter try: frontmatter = yaml.safe_load(frontmatter_text) if not isinstance(frontmatter, dict): return False, "Frontmatter must be a YAML dictionary" except yaml.YAMLError as e: return False, f"Invalid YAML in frontmatter: {e}" # Define allowed properties ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata', 'compatibility'} # Check for unexpected properties (excluding nested keys under metadata) unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES if unexpected_keys: return False, ( f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. " f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}" ) # Check required fields if 'name' not in frontmatter: return False, "Missing 'name' in frontmatter" if 'description' not in frontmatter: return False, "Missing 'description' in frontmatter" # Extract name for validation name = frontmatter.get('name', '') if not isinstance(name, str): return False, f"Name must be a string, got {type(name).__name__}" name = name.strip() if name: # Check naming convention (kebab-case: lowercase with hyphens) if not re.match(r'^[a-z0-9-]+$', name): return False, f"Name '{name}' should be kebab-case (lowercase letters, digits, and hyphens only)" if name.startswith('-') or name.endswith('-') or '--' in name: return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens" # Check name length (max 64 characters per spec) if len(name) > 64: return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters." # Extract and validate description description = frontmatter.get('description', '') if not isinstance(description, str): return False, f"Description must be a string, got {type(description).__name__}" description = description.strip() if description: # Check for angle brackets if '<' in description or '>' in description: return False, "Description cannot contain angle brackets (< or >)" # Check description length (max 1024 characters per spec) if len(description) > 1024: return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters." # Validate compatibility field if present (optional) compatibility = frontmatter.get('compatibility', '') if compatibility: if not isinstance(compatibility, str): return False, f"Compatibility must be a string, got {type(compatibility).__name__}" if len(compatibility) > 500: return False, f"Compatibility is too long ({len(compatibility)} characters). Maximum is 500 characters." return True, "Skill is valid!" if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python quick_validate.py ") sys.exit(1) valid, message = validate_skill(sys.argv[1]) print(message) sys.exit(0 if valid else 1) ================================================ FILE: .claude/skills/skill-creator/scripts/run_eval.py ================================================ #!/usr/bin/env python3 """Run trigger evaluation for a skill description. Tests whether a skill's description causes Claude to trigger (read the skill) for a set of queries. Outputs results as JSON. """ import argparse import json import os import select import subprocess import sys import time import uuid from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path from scripts.utils import parse_skill_md def find_project_root() -> Path: """Find the project root by walking up from cwd looking for .claude/. Mimics how Claude Code discovers its project root, so the command file we create ends up where claude -p will look for it. """ current = Path.cwd() for parent in [current, *current.parents]: if (parent / ".claude").is_dir(): return parent return current def run_single_query( query: str, skill_name: str, skill_description: str, timeout: int, project_root: str, model: str | None = None, ) -> bool: """Run a single query and return whether the skill was triggered. Creates a command file in .claude/commands/ so it appears in Claude's available_skills list, then runs `claude -p` with the raw query. Uses --include-partial-messages to detect triggering early from stream events (content_block_start) rather than waiting for the full assistant message, which only arrives after tool execution. """ unique_id = uuid.uuid4().hex[:8] clean_name = f"{skill_name}-skill-{unique_id}" project_commands_dir = Path(project_root) / ".claude" / "commands" command_file = project_commands_dir / f"{clean_name}.md" try: project_commands_dir.mkdir(parents=True, exist_ok=True) # Use YAML block scalar to avoid breaking on quotes in description indented_desc = "\n ".join(skill_description.split("\n")) command_content = ( f"---\n" f"description: |\n" f" {indented_desc}\n" f"---\n\n" f"# {skill_name}\n\n" f"This skill handles: {skill_description}\n" ) command_file.write_text(command_content) cmd = [ "claude", "-p", query, "--output-format", "stream-json", "--verbose", "--include-partial-messages", ] if model: cmd.extend(["--model", model]) # Remove CLAUDECODE env var to allow nesting claude -p inside a # Claude Code session. The guard is for interactive terminal conflicts; # programmatic subprocess usage is safe. env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"} process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=project_root, env=env, ) triggered = False start_time = time.time() buffer = "" # Track state for stream event detection pending_tool_name = None accumulated_json = "" try: while time.time() - start_time < timeout: if process.poll() is not None: remaining = process.stdout.read() if remaining: buffer += remaining.decode("utf-8", errors="replace") break ready, _, _ = select.select([process.stdout], [], [], 1.0) if not ready: continue chunk = os.read(process.stdout.fileno(), 8192) if not chunk: break buffer += chunk.decode("utf-8", errors="replace") while "\n" in buffer: line, buffer = buffer.split("\n", 1) line = line.strip() if not line: continue try: event = json.loads(line) except json.JSONDecodeError: continue # Early detection via stream events if event.get("type") == "stream_event": se = event.get("event", {}) se_type = se.get("type", "") if se_type == "content_block_start": cb = se.get("content_block", {}) if cb.get("type") == "tool_use": tool_name = cb.get("name", "") if tool_name in ("Skill", "Read"): pending_tool_name = tool_name accumulated_json = "" else: return False elif se_type == "content_block_delta" and pending_tool_name: delta = se.get("delta", {}) if delta.get("type") == "input_json_delta": accumulated_json += delta.get("partial_json", "") if clean_name in accumulated_json: return True elif se_type in ("content_block_stop", "message_stop"): if pending_tool_name: return clean_name in accumulated_json if se_type == "message_stop": return False # Fallback: full assistant message elif event.get("type") == "assistant": message = event.get("message", {}) for content_item in message.get("content", []): if content_item.get("type") != "tool_use": continue tool_name = content_item.get("name", "") tool_input = content_item.get("input", {}) if tool_name == "Skill" and clean_name in tool_input.get("skill", ""): triggered = True elif tool_name == "Read" and clean_name in tool_input.get("file_path", ""): triggered = True return triggered elif event.get("type") == "result": return triggered finally: # Clean up process on any exit path (return, exception, timeout) if process.poll() is None: process.kill() process.wait() return triggered finally: if command_file.exists(): command_file.unlink() def run_eval( eval_set: list[dict], skill_name: str, description: str, num_workers: int, timeout: int, project_root: Path, runs_per_query: int = 1, trigger_threshold: float = 0.5, model: str | None = None, ) -> dict: """Run the full eval set and return results.""" results = [] with ProcessPoolExecutor(max_workers=num_workers) as executor: future_to_info = {} for item in eval_set: for run_idx in range(runs_per_query): future = executor.submit( run_single_query, item["query"], skill_name, description, timeout, str(project_root), model, ) future_to_info[future] = (item, run_idx) query_triggers: dict[str, list[bool]] = {} query_items: dict[str, dict] = {} for future in as_completed(future_to_info): item, _ = future_to_info[future] query = item["query"] query_items[query] = item if query not in query_triggers: query_triggers[query] = [] try: query_triggers[query].append(future.result()) except Exception as e: print(f"Warning: query failed: {e}", file=sys.stderr) query_triggers[query].append(False) for query, triggers in query_triggers.items(): item = query_items[query] trigger_rate = sum(triggers) / len(triggers) should_trigger = item["should_trigger"] if should_trigger: did_pass = trigger_rate >= trigger_threshold else: did_pass = trigger_rate < trigger_threshold results.append({ "query": query, "should_trigger": should_trigger, "trigger_rate": trigger_rate, "triggers": sum(triggers), "runs": len(triggers), "pass": did_pass, }) passed = sum(1 for r in results if r["pass"]) total = len(results) return { "skill_name": skill_name, "description": description, "results": results, "summary": { "total": total, "passed": passed, "failed": total - passed, }, } def main(): parser = argparse.ArgumentParser(description="Run trigger evaluation for a skill description") parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file") parser.add_argument("--skill-path", required=True, help="Path to skill directory") parser.add_argument("--description", default=None, help="Override description to test") parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers") parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds") parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query") parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold") parser.add_argument("--model", default=None, help="Model to use for claude -p (default: user's configured model)") parser.add_argument("--verbose", action="store_true", help="Print progress to stderr") args = parser.parse_args() eval_set = json.loads(Path(args.eval_set).read_text()) skill_path = Path(args.skill_path) if not (skill_path / "SKILL.md").exists(): print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) sys.exit(1) name, original_description, content = parse_skill_md(skill_path) description = args.description or original_description project_root = find_project_root() if args.verbose: print(f"Evaluating: {description}", file=sys.stderr) output = run_eval( eval_set=eval_set, skill_name=name, description=description, num_workers=args.num_workers, timeout=args.timeout, project_root=project_root, runs_per_query=args.runs_per_query, trigger_threshold=args.trigger_threshold, model=args.model, ) if args.verbose: summary = output["summary"] print(f"Results: {summary['passed']}/{summary['total']} passed", file=sys.stderr) for r in output["results"]: status = "PASS" if r["pass"] else "FAIL" rate_str = f"{r['triggers']}/{r['runs']}" print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:70]}", file=sys.stderr) print(json.dumps(output, indent=2)) if __name__ == "__main__": main() ================================================ FILE: .claude/skills/skill-creator/scripts/run_loop.py ================================================ #!/usr/bin/env python3 """Run the eval + improve loop until all pass or max iterations reached. Combines run_eval.py and improve_description.py in a loop, tracking history and returning the best description found. Supports train/test split to prevent overfitting. """ import argparse import json import random import sys import tempfile import time import webbrowser from pathlib import Path import anthropic from scripts.generate_report import generate_html from scripts.improve_description import improve_description from scripts.run_eval import find_project_root, run_eval from scripts.utils import parse_skill_md def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]: """Split eval set into train and test sets, stratified by should_trigger.""" random.seed(seed) # Separate by should_trigger trigger = [e for e in eval_set if e["should_trigger"]] no_trigger = [e for e in eval_set if not e["should_trigger"]] # Shuffle each group random.shuffle(trigger) random.shuffle(no_trigger) # Calculate split points n_trigger_test = max(1, int(len(trigger) * holdout)) n_no_trigger_test = max(1, int(len(no_trigger) * holdout)) # Split test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test] train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:] return train_set, test_set def run_loop( eval_set: list[dict], skill_path: Path, description_override: str | None, num_workers: int, timeout: int, max_iterations: int, runs_per_query: int, trigger_threshold: float, holdout: float, model: str, verbose: bool, live_report_path: Path | None = None, log_dir: Path | None = None, ) -> dict: """Run the eval + improvement loop.""" project_root = find_project_root() name, original_description, content = parse_skill_md(skill_path) current_description = description_override or original_description # Split into train/test if holdout > 0 if holdout > 0: train_set, test_set = split_eval_set(eval_set, holdout) if verbose: print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr) else: train_set = eval_set test_set = [] client = anthropic.Anthropic() history = [] exit_reason = "unknown" for iteration in range(1, max_iterations + 1): if verbose: print(f"\n{'='*60}", file=sys.stderr) print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr) print(f"Description: {current_description}", file=sys.stderr) print(f"{'='*60}", file=sys.stderr) # Evaluate train + test together in one batch for parallelism all_queries = train_set + test_set t0 = time.time() all_results = run_eval( eval_set=all_queries, skill_name=name, description=current_description, num_workers=num_workers, timeout=timeout, project_root=project_root, runs_per_query=runs_per_query, trigger_threshold=trigger_threshold, model=model, ) eval_elapsed = time.time() - t0 # Split results back into train/test by matching queries train_queries_set = {q["query"] for q in train_set} train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set] test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set] train_passed = sum(1 for r in train_result_list if r["pass"]) train_total = len(train_result_list) train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total} train_results = {"results": train_result_list, "summary": train_summary} if test_set: test_passed = sum(1 for r in test_result_list if r["pass"]) test_total = len(test_result_list) test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total} test_results = {"results": test_result_list, "summary": test_summary} else: test_results = None test_summary = None history.append({ "iteration": iteration, "description": current_description, "train_passed": train_summary["passed"], "train_failed": train_summary["failed"], "train_total": train_summary["total"], "train_results": train_results["results"], "test_passed": test_summary["passed"] if test_summary else None, "test_failed": test_summary["failed"] if test_summary else None, "test_total": test_summary["total"] if test_summary else None, "test_results": test_results["results"] if test_results else None, # For backward compat with report generator "passed": train_summary["passed"], "failed": train_summary["failed"], "total": train_summary["total"], "results": train_results["results"], }) # Write live report if path provided if live_report_path: partial_output = { "original_description": original_description, "best_description": current_description, "best_score": "in progress", "iterations_run": len(history), "holdout": holdout, "train_size": len(train_set), "test_size": len(test_set), "history": history, } live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name)) if verbose: def print_eval_stats(label, results, elapsed): pos = [r for r in results if r["should_trigger"]] neg = [r for r in results if not r["should_trigger"]] tp = sum(r["triggers"] for r in pos) pos_runs = sum(r["runs"] for r in pos) fn = pos_runs - tp fp = sum(r["triggers"] for r in neg) neg_runs = sum(r["runs"] for r in neg) tn = neg_runs - fp total = tp + tn + fp + fn precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0 recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0 accuracy = (tp + tn) / total if total > 0 else 0.0 print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr) for r in results: status = "PASS" if r["pass"] else "FAIL" rate_str = f"{r['triggers']}/{r['runs']}" print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr) print_eval_stats("Train", train_results["results"], eval_elapsed) if test_summary: print_eval_stats("Test ", test_results["results"], 0) if train_summary["failed"] == 0: exit_reason = f"all_passed (iteration {iteration})" if verbose: print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr) break if iteration == max_iterations: exit_reason = f"max_iterations ({max_iterations})" if verbose: print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr) break # Improve the description based on train results if verbose: print(f"\nImproving description...", file=sys.stderr) t0 = time.time() # Strip test scores from history so improvement model can't see them blinded_history = [ {k: v for k, v in h.items() if not k.startswith("test_")} for h in history ] new_description = improve_description( client=client, skill_name=name, skill_content=content, current_description=current_description, eval_results=train_results, history=blinded_history, model=model, log_dir=log_dir, iteration=iteration, ) improve_elapsed = time.time() - t0 if verbose: print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr) current_description = new_description # Find the best iteration by TEST score (or train if no test set) if test_set: best = max(history, key=lambda h: h["test_passed"] or 0) best_score = f"{best['test_passed']}/{best['test_total']}" else: best = max(history, key=lambda h: h["train_passed"]) best_score = f"{best['train_passed']}/{best['train_total']}" if verbose: print(f"\nExit reason: {exit_reason}", file=sys.stderr) print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr) return { "exit_reason": exit_reason, "original_description": original_description, "best_description": best["description"], "best_score": best_score, "best_train_score": f"{best['train_passed']}/{best['train_total']}", "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None, "final_description": current_description, "iterations_run": len(history), "holdout": holdout, "train_size": len(train_set), "test_size": len(test_set), "history": history, } def main(): parser = argparse.ArgumentParser(description="Run eval + improve loop") parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file") parser.add_argument("--skill-path", required=True, help="Path to skill directory") parser.add_argument("--description", default=None, help="Override starting description") parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers") parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds") parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations") parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query") parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold") parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)") parser.add_argument("--model", required=True, help="Model for improvement") parser.add_argument("--verbose", action="store_true", help="Print progress to stderr") parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)") parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here") args = parser.parse_args() eval_set = json.loads(Path(args.eval_set).read_text()) skill_path = Path(args.skill_path) if not (skill_path / "SKILL.md").exists(): print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) sys.exit(1) name, _, _ = parse_skill_md(skill_path) # Set up live report path if args.report != "none": if args.report == "auto": timestamp = time.strftime("%Y%m%d_%H%M%S") live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html" else: live_report_path = Path(args.report) # Open the report immediately so the user can watch live_report_path.write_text("

Starting optimization loop...

") webbrowser.open(str(live_report_path)) else: live_report_path = None # Determine output directory (create before run_loop so logs can be written) if args.results_dir: timestamp = time.strftime("%Y-%m-%d_%H%M%S") results_dir = Path(args.results_dir) / timestamp results_dir.mkdir(parents=True, exist_ok=True) else: results_dir = None log_dir = results_dir / "logs" if results_dir else None output = run_loop( eval_set=eval_set, skill_path=skill_path, description_override=args.description, num_workers=args.num_workers, timeout=args.timeout, max_iterations=args.max_iterations, runs_per_query=args.runs_per_query, trigger_threshold=args.trigger_threshold, holdout=args.holdout, model=args.model, verbose=args.verbose, live_report_path=live_report_path, log_dir=log_dir, ) # Save JSON output json_output = json.dumps(output, indent=2) print(json_output) if results_dir: (results_dir / "results.json").write_text(json_output) # Write final HTML report (without auto-refresh) if live_report_path: live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name)) print(f"\nReport: {live_report_path}", file=sys.stderr) if results_dir and live_report_path: (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name)) if results_dir: print(f"Results saved to: {results_dir}", file=sys.stderr) if __name__ == "__main__": main() ================================================ FILE: .claude/skills/skill-creator/scripts/utils.py ================================================ """Shared utilities for skill-creator scripts.""" from pathlib import Path def parse_skill_md(skill_path: Path) -> tuple[str, str, str]: """Parse a SKILL.md file, returning (name, description, full_content).""" content = (skill_path / "SKILL.md").read_text() lines = content.split("\n") if lines[0].strip() != "---": raise ValueError("SKILL.md missing frontmatter (no opening ---)") end_idx = None for i, line in enumerate(lines[1:], start=1): if line.strip() == "---": end_idx = i break if end_idx is None: raise ValueError("SKILL.md missing frontmatter (no closing ---)") name = "" description = "" frontmatter_lines = lines[1:end_idx] i = 0 while i < len(frontmatter_lines): line = frontmatter_lines[i] if line.startswith("name:"): name = line[len("name:"):].strip().strip('"').strip("'") elif line.startswith("description:"): value = line[len("description:"):].strip() # Handle YAML multiline indicators (>, |, >-, |-) if value in (">", "|", ">-", "|-"): continuation_lines: list[str] = [] i += 1 while i < len(frontmatter_lines) and (frontmatter_lines[i].startswith(" ") or frontmatter_lines[i].startswith("\t")): continuation_lines.append(frontmatter_lines[i].strip()) i += 1 description = " ".join(continuation_lines) continue else: description = value.strip('"').strip("'") i += 1 return name, description, content ================================================ FILE: .gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /dist /dst .idea first dst-admin-go dst-admin-go.exe dst-admin-go.log dst-db password.txt /.pnp .pnp.js # testing /coverage .vscode # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* #py-dst-cli /script/py-dst-cli/__pycache__ /script/py-dst-cli/data /test ================================================ FILE: CLAUDE.md ================================================ # CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview DST Admin Go is a web-based management panel for "Don't Starve Together" game servers. Written in Go, it provides a simple deployment, low memory footprint, and visual interface for managing game configurations, mods, clusters, backups, and multi-server operations across both Windows and Linux platforms. ## Development Commands ### Running the Application ```bash # Install dependencies go mod tidy # Run the application go run cmd/server/main.go ``` The server starts on port 8082 by default (configurable in `config.yml`). ### Building ```bash # Build for Linux bash scripts/build_linux.sh # Output: dst-admin-go (Linux amd64 binary) # Build for Windows bash scripts/build_window.sh # Output: dst-admin-go.exe (Windows amd64 binary) # Cross-platform build from Windows to Linux set GOARCH=amd64 set GOOS=linux go build ``` ### Testing No test files currently exist in the project. When writing tests, place them adjacent to the code they test with `_test.go` suffix. ## Code Architecture ### Entry Point - **Main entry**: `cmd/server/main.go` - Loads config, initializes database, sets up router, and starts the HTTP server. ### Project Structure ``` dst-admin-go/ ├── cmd/server/ # Application entry point ├── internal/ # Private application code │ ├── api/ # HTTP layer │ │ ├── handler/ # HTTP handlers (controllers) │ │ └── router.go # Route registration and DI setup │ ├── config/ # Configuration loading │ ├── database/ # Database initialization │ ├── middleware/ # HTTP middleware (auth, error handling, cluster context) │ ├── model/ # Database models (GORM entities) │ ├── pkg/ # Internal shared utilities │ │ ├── response/ # Standard HTTP response helpers │ │ └── utils/ # Utility functions (file, shell, system, etc.) │ └── service/ # Business logic layer │ ├── archive/ # Archive path resolution │ ├── backup/ # Backup management │ ├── dstConfig/ # DST configuration management │ ├── dstPath/ # Platform-specific path handling │ ├── game/ # Game process management (start/stop/command) │ ├── gameArchive/ # Game archive operations │ ├── gameConfig/ # Game configuration files │ ├── level/ # Level (world) management │ ├── levelConfig/ # Level configuration parsing │ ├── login/ # Authentication │ ├── mod/ # Mod management │ ├── player/ # Player management │ └── update/ # Game update management ├── scripts/ # Build and utility scripts └── config.yml # Application configuration file ``` ### Layered Architecture The codebase follows a three-layer architecture: 1. **Handler Layer** (`internal/api/handler/`): HTTP request handling, input validation, response formatting 2. **Service Layer** (`internal/service/`): Business logic, orchestration between services 3. **Model Layer** (`internal/model/`): Database entities (GORM models) ### Dependency Injection All services are instantiated in `internal/api/router.go` using constructor functions (`New{Service}Service`), then injected into handlers. This pattern: - Avoids global variables - Makes dependencies explicit - Enables testing with mock implementations Example flow: ``` router.go creates services → injects into handlers → handlers registered to routes ``` ### Platform Abstraction Services use factory patterns for platform-specific implementations: - **Game Process**: `game.NewGame()` returns `LinuxProcess` or `WindowProcess` based on `runtime.GOOS` - **Update Service**: `update.NewUpdateService()` handles Linux/Windows differences - **DST Paths**: `dstPath` package provides platform-specific path resolution ### Service Interfaces Core services define interfaces for flexibility and testing: - `dstConfig.Config`: DST configuration CRUD operations - `game.Process`: Game server lifecycle management - Simpler services may omit interfaces and use concrete types directly ## Configuration The application reads `config.yml` in the working directory: ```yaml bindAddress: "" # Bind address (empty = all interfaces) port: 8082 # HTTP server port database: dst-db # SQLite database filename steamAPIKey: "" # Steam API key (optional) autoCheck: # Auto-check intervals (in minutes) masterInterval: 5 cavesInterval: 5 masterModInterval: 10 # ... other intervals ``` ## Database - **ORM**: GORM with SQLite (via glebarez/sqlite) - **Initialization**: `internal/database/sqlite.go` - Auto-migrates all models in `internal/model/` - **Models**: Represent game data (clusters, players, mods, backups, logs, etc.) ## API Refactoring Guidelines The project is undergoing a refactoring effort documented in `.sisyphus/plans/`. Key principles: ### Code Organization Rules 1. **No global variables**: Pass config and dependencies through constructors 2. **No constants package**: Define constants locally using `const ()` blocks within each module 3. **No VO suffix**: Data structures defined in services use PascalCase without VO suffix 4. **Internal-only changes**: Do not modify code outside `internal/` directory 5. **Dependency injection**: All service dependencies injected via constructors ### Handler Pattern Each handler: - Is in `internal/api/handler/{name}_handler.go` - Has a `RegisterRoute(router *gin.RouterGroup)` method - Uses injected services for business logic - Uses `internal/pkg/response` for standardized responses ### Service Pattern Each service: - Is in `internal/service/{domain}/` directory - Has a constructor `New{Service}Service()` accepting dependencies - Defines interfaces for core abstractions (optional for simple services) - Handles a single domain of business logic ### Naming Conventions - **Files**: `snake_case.go` (e.g., `backup_service.go`) - **Interfaces**: `{ServiceName}` (e.g., `Config`, `Process`) - **Structs**: `PascalCase` without suffix (e.g., `BackupSnapshot` not `BackupSnapshotVO`) - **Constructors**: `New{Name}` (e.g., `NewBackupService`) ## Game Server Management The application manages Don't Starve Together dedicated servers: - **Clusters**: A cluster contains multiple "levels" (worlds) - typically Master (overworld) and Caves - **Process Management**: Uses platform-specific commands (screen/tmux on Linux, custom CLI on Windows) - **Configuration Files**: Parses and modifies Lua config files (`cluster.ini`, `leveldataoverride.lua`, `modoverrides.lua`) - **Session Names**: Identifies running processes by cluster and level names ## Utilities Common utilities in `internal/pkg/utils/`: - **fileUtils**: File operations, archive extraction - **shellUtils**: Execute shell commands - **systemUtils**: System information (CPU, memory) - **dstConfigUtils**: DST config file parsing - **luaUtils**: Lua table parsing/generation - **collectionUtils**: Slice/map helpers - **clusterUtils**: Cluster-specific utilities ## Development Notes - Go version: 1.20+ - Web framework: Gin - Session management: gin-contrib/sessions with memstore - Authentication: Session-based, checked via `middleware.Authentication` - All routes except `/hello` and login endpoints require authentication - Chinese comments and messages common in codebase (target audience is Chinese users) ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README-EN.md ================================================ # dst-admin-go > dst-admin-go manage web > > preview https://carrot-hu23.github.io/dst-admin-go-preview/ [English](README-EN.md)/[中文](README.md) **Now supports both Windows and Linux platforms** ## About DST Admin Go is a web-based management panel for "Don't Starve Together" dedicated servers, written in Go. Key features include: - 🚀 **Easy Deployment**: Single executable binary, no complex configuration required - 💾 **Low Resource Usage**: Built with Go, minimal memory footprint and high performance - 🎨 **Modern UI**: Clean and intuitive web interface - ⚙️ **Feature-Rich**: - Visual configuration for game rooms and world settings - Online mod management and configuration - Multi-cluster and multi-world support - Game save backup and snapshot restoration - Player management (whitelist, blacklist, administrators) - Real-time log viewing and game console access - Automatic game server update detection ## Preview ![首页效果](docs/image/dashboard.png) ![首页效果](docs/image/panel.png) ![首页效果](docs/image/toomanyitemplus.png) ![首页效果](docs/image/player.png) ![房间效果](docs/image/home.png) ![世界效果](docs/image/level.png) ![世界效果](docs/image/selectormod.png) ![模组效果](docs/image/mod1.png) ![模组效果](docs/image/mod3.png) ![模组效果](docs/image/mod2.png) ![日志效果](docs/image/playerlog.png) ![大厅效果](docs/image/lobby.png) ## Run **Edit config.yml** ```yaml # Bind address bindAddress: "" # Port port: 8082 # Database database: dst-db ``` Run ```bash go mod tidy go run cmd/server/main.go ``` ## Build ### Build for Linux ```bash bash scripts/build_linux.sh # Output: dst-admin-go (Linux amd64 binary) ``` ### Build for Windows ```bash bash scripts/build_window.sh # Output: dst-admin-go.exe (Windows amd64 binary) ``` ### Cross-compile from Windows to Linux ```cmd # Open cmd set GOARCH=amd64 set GOOS=linux go build -o dst-admin-go cmd/server/main.go ``` ## QQ Group ![QQ 群](docs/image/饥荒开服面板交流issue群聊二维码.png) ================================================ FILE: README.md ================================================ # dst-admin-go > 饥荒联机版管理后台 > > 预览 https://carrot-hu23.github.io/dst-admin-go-preview/ [English](README-EN.md)/[中文](README.md) **新面板 [泰拉瑞亚面板](https://github.com/carrot-hu23/terraria-panel-app) 支持window,linux 一键启动,内置 1449 版本** ## 推广 **广告位招租,联系QQ 1762858544** [【腾讯云】热卖套餐配置低至32元/月起,助您一键开服,即刻畅玩,立享优惠!](https://cloud.tencent.com/act/cps/redirect?redirect=5878&cps_key=8478a20880d339923787a350f9f8cbf5&from=console) ![tengxunad1](docs/image/tengxunad1.png) ## 项目简介 **现已支持 Windows 和 Linux 平台** > 注意:Windows Server 低版本系统请使用 1.2.8 之前的版本,高版本系统使用最新版本 DST Admin Go 是一个使用 Go 语言开发的《饥荒联机版》服务器管理面板,具有以下特点: - 🚀 **部署简单**:单个可执行文件,无需复杂配置,开箱即用 - 💾 **资源占用低**:基于 Go 语言开发,内存占用小,运行高效 - 🎨 **界面美观**:现代化的 Web 界面,操作直观友好 - ⚙️ **功能完善**: - 可视化配置游戏房间和世界参数 - 在线管理和配置 Mod(模组) - 支持多个集群(Cluster)和世界的统一管理 - 游戏存档备份与快照恢复 - 玩家管理(白名单、黑名单、管理员) - 实时日志查看和游戏控制台 - 游戏服务器自动更新检测 ## 部署 注意目录必须要有读写权限。 点击查看 [部署文档](https://carrot-hu23.github.io/dst-admin-go-docs/) ## 预览 ![首页效果](docs/image/dashboard.png) ![首页效果](docs/image/panel.png) ![首页效果](docs/image/toomanyitemplus.png) ![首页效果](docs/image/player.png) ![房间效果](docs/image/home.png) ![世界效果](docs/image/level.png) ![世界效果](docs/image/selectormod.png) ![模组效果](docs/image/mod1.png) ![模组效果](docs/image/mod3.png) ![模组效果](docs/image/mod2.png) ![日志效果](docs/image/playerlog.png) ![大厅效果](docs/image/lobby.png) ## 运行 **修改config.yml** ```yaml #绑定地址 bindAddress: "" #启动端口 port: 8082 #数据库 database: dst-db ``` 运行 ```bash go mod tidy go run cmd/server/main.go ``` ## 打包 ### Linux 打包 ```bash bash scripts/build_linux.sh # 输出: dst-admin-go (Linux amd64 二进制文件) ``` ### Windows 打包 ```bash bash scripts/build_window.sh # 输出: dst-admin-go.exe (Windows amd64 二进制文件) ``` ### Window 下打包 Linux 二进制 ```cmd 打开 cmd set GOARCH=amd64 set GOOS=linux go build -o dst-admin-go cmd/server/main.go ``` ## QQ 群 ![QQ 群](docs/image/饥荒开服面板交流issue群聊二维码.png) ================================================ FILE: cmd/server/main.go ================================================ // @title DST Admin Go API // @version 1.0 // @description 饥荒联机版服务器管理后台 API 文档 // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url https://github.com/carrot-hu23/dst-admin-go // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host localhost:8082 // @BasePath / // @securityDefinitions.apikey BearerAuth // @in header // @name Authorization // @description Type "Bearer" followed by a space and JWT token. package main import ( "dst-admin-go/internal/api" "dst-admin-go/internal/config" "dst-admin-go/internal/database" "fmt" ) func main() { cfg := config.Load() db := database.InitDB(cfg) route := api.NewRoute(cfg, db) err := route.Run(cfg.BindAddress + ":" + cfg.Port) if err != nil { fmt.Println("启动失败!!!", err) } } ================================================ FILE: config.yml ================================================ #绑定地址 bindAddress: "" #启动端口 port: 8082 #数据库 database: dst-db #自动检测 单位都是 分钟 autoCheck: # 森林状态检测间隔时间 masterInterval: 5 # 洞穴状态检测间隔时间 cavesInterval: 5 # 森林模组更新检测间隔时间 masterModInterval: 10 # 洞穴模组更新检测间隔时间 cavesIModInterval: 10 # 游戏更新检测间隔时间 gameUpdateInterval: 20 modUpdatePrompt: "xxx" gameUpdatePrompt: "xxx" ================================================ FILE: docs/docs.go ================================================ // Package docs Code generated by swaggo/swag. DO NOT EDIT package docs import "github.com/swaggo/swag" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "API Support", "url": "https://github.com/carrot-hu23/dst-admin-go" }, "license": { "name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" }, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/api/cluster/level": { "get": { "description": "获取指定世界的详细信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "获取单个世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "put": { "description": "批量更新多个世界的配置信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "批量更新世界", "parameters": [ { "description": "世界配置信息列表", "name": "levels", "in": "body", "required": true, "schema": { "type": "array", "items": { "$ref": "#/definitions/levelConfig.LevelInfo" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "创建一个新的世界(等级)", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "创建世界", "parameters": [ { "description": "世界配置信息", "name": "level", "in": "body", "required": true, "schema": { "$ref": "#/definitions/levelConfig.LevelInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "delete": { "description": "删除指定的世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "删除世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/gen": { "get": { "description": "生成地图", "tags": [ "dstMap" ], "summary": "生成地图", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/has/walrusHut/plains": { "get": { "description": "检测地图中是否有walrusHutPlains", "tags": [ "dstMap" ], "summary": "检测地图中是否有walrusHutPlains", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/image": { "get": { "description": "获取地图图片", "tags": [ "dstMap" ], "summary": "获取地图图片", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/player/session/file": { "get": { "description": "获取玩家存档文件", "tags": [ "dstMap" ], "summary": "获取玩家存档文件", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/session/file": { "get": { "description": "获取存档文件", "tags": [ "dstMap" ], "summary": "获取存档文件", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/8level/status": { "get": { "description": "获取所有世界的运行状态信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "获取服务器状态", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/definitions/handler.LevelStatus" } } } } ] } } } } }, "/api/game/archive": { "get": { "description": "获取当前集群的游戏存档列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "获取游戏存档列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup": { "get": { "description": "获取当前集群的所有备份文件列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "获取备份列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "put": { "description": "重命名指定的备份文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "重命名备份", "parameters": [ { "description": "请求体", "name": "request", "in": "body", "required": true, "schema": { "type": "object" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "创建新的游戏存档备份", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "创建备份", "parameters": [ { "type": "string", "description": "备份名称", "name": "backupName", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "delete": { "description": "删除指定的备份文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "删除备份", "parameters": [ { "description": "要删除的文件名列表", "name": "fileNames", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/download": { "get": { "description": "下载指定的备份文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "下载备份", "parameters": [ { "type": "string", "description": "备份文件名", "name": "backupName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/snapshot/list": { "get": { "description": "获取当前集群的所有快照备份列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "获取快照列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/snapshot/setting": { "get": { "description": "获取自动快照备份的设置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "获取快照设置", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "保存自动快照备份的设置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "保存快照设置", "parameters": [ { "description": "快照设置", "name": "setting", "in": "body", "required": true, "schema": { "$ref": "#/definitions/model.BackupSnapshot" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/upload": { "post": { "description": "上传新的备份文件", "consumes": [ "multipart/form-data" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "上传备份", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/command": { "post": { "description": "运行命令", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "运行命令", "parameters": [ { "type": "string", "description": "命令", "name": "command", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config": { "get": { "description": "获取房间配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/gameConfig.HomeConfigVO" } } } ] } } } } }, "/api/game/config/adminlist": { "get": { "description": "获取房间 adminlist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 adminlist.txt 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } }, "post": { "description": "保存房间 adminlist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 adminlist.txt 配置", "parameters": [ { "description": "adminlist.txt 配置", "name": "list", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config/blacklist": { "get": { "description": "获取房间 blacklist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 blacklist.txt 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } }, "post": { "description": "保存房间 blacklist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 blacklist.txt 配置", "parameters": [ { "description": "blacklist.txt 配置", "name": "list", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config/clusterIni": { "get": { "description": "获取房间 cluster.ini 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 cluster.ini 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/gameConfig.ClusterIniConfig" } } } ] } } } }, "post": { "description": "保存房间 cluster.ini 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 cluster.ini 配置", "parameters": [ { "description": "cluster.ini 配置", "name": "config", "in": "body", "required": true, "schema": { "$ref": "#/definitions/gameConfig.ClusterIniConfig" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config/whitelist": { "get": { "description": "获取房间 whitelist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 whitelist.txt 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } }, "post": { "description": "保存房间 whitelist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 whitelist.txt 配置", "parameters": [ { "description": "whitelist.txt 配置", "name": "list", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/dst/config": { "get": { "description": "获取房间 dst 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "dstConfig" ], "summary": "获取房间 dst 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/dstConfig.DstConfig" } } } ] } } } }, "post": { "description": "保存房间 dst 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "dstConfig" ], "summary": "保存房间 dst 配置", "parameters": [ { "description": "dst 配置", "name": "config", "in": "body", "required": true, "schema": { "$ref": "#/definitions/dstConfig.DstConfig" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/level/server/download": { "get": { "description": "下载指定世界的完整服务器日志文件", "produces": [ "application/octet-stream" ], "tags": [ "log" ], "summary": "下载服务器日志", "parameters": [ { "type": "string", "description": "集群名称", "name": "clusterName", "in": "query" }, { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "服务器日志文件", "schema": { "type": "file" } } } } }, "/api/game/level/server/log": { "get": { "description": "获取指定世界的服务器日志(默认最近100行)", "produces": [ "application/json" ], "tags": [ "log" ], "summary": "获取服务器日志", "parameters": [ { "type": "string", "description": "集群名称", "name": "clusterName", "in": "query" }, { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true }, { "type": "string", "description": "返回日志行数,默认为100", "name": "lines", "in": "query" } ], "responses": { "200": { "description": "服务器日志列表", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } } }, "/api/game/log/stream": { "get": { "description": "获取指定世界的实时日志流 (SSE)", "consumes": [ "text/event-stream" ], "produces": [ "text/event-stream" ], "tags": [ "log" ], "summary": "服务器日志流", "parameters": [ { "type": "string", "description": "集群名称", "name": "clusterName", "in": "query" }, { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "SSE 格式的日志流", "schema": { "type": "string" } } } } }, "/api/game/start": { "get": { "description": "启动世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "启动世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/start/all": { "get": { "description": "启动所有世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "启动所有世界", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/stop": { "get": { "description": "停止世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "停止世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/stop/all": { "get": { "description": "停止所有世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "停止所有世界", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/system/info/stream": { "get": { "description": "获取服务器系统信息的实时流 (SSE)", "consumes": [ "text/event-stream" ], "produces": [ "text/event-stream" ], "tags": [ "game" ], "summary": "系统信息流", "responses": { "200": { "description": "SSE 格式的系统信息流", "schema": { "type": "string" } } } } }, "/api/game/update": { "get": { "description": "更新游戏", "tags": [ "update" ], "summary": "更新游戏", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/init": { "get": { "description": "检查系统是否进行了首次初始化", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "检查是否首次初始化", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "初始化系统首次用户信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "初始化首次用户", "parameters": [ { "description": "用户信息", "name": "userInfo", "in": "body", "required": true, "schema": { "$ref": "#/definitions/login.UserInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/kv": { "get": { "description": "获取kv值", "tags": [ "kv" ], "summary": "获取kv值", "parameters": [ { "type": "string", "description": "key", "name": "key", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "保存kv值", "tags": [ "kv" ], "summary": "保存kv值", "parameters": [ { "type": "string", "description": "key", "name": "key", "in": "formData", "required": true }, { "type": "string", "description": "value", "name": "value", "in": "formData", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod": { "get": { "description": "获取已订阅的模组列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取我的mod列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/modinfo": { "put": { "description": "批量更新所有已订阅模组的信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "批量更新模组信息", "parameters": [ { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "保存模组配置信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "保存模组配置文件", "parameters": [ { "description": "模组信息", "name": "data", "in": "body", "required": true, "schema": { "$ref": "#/definitions/mod.ModInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/mod.ModInfo" } } } ] } } } } }, "/api/mod/modinfo/file": { "post": { "description": "手动添加模组配置文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "手动添加模组", "parameters": [ { "description": "模组信息", "name": "data", "in": "body", "required": true, "schema": { "type": "object" } }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/modinfo/{modId}": { "get": { "description": "根据modId获取模组配置文件内容", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取模组配置文件", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/mod.ModInfo" } } } ] } } } } }, "/api/mod/search": { "get": { "description": "搜索Steam创意工坊中的模组", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "搜索mod列表", "parameters": [ { "type": "string", "description": "搜索关键词", "name": "text", "in": "query" }, { "type": "integer", "default": 1, "description": "页码", "name": "page", "in": "query" }, { "type": "integer", "default": 10, "description": "每页数量", "name": "size", "in": "query" }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/setup/workshop": { "delete": { "description": "删除所有workshop模组文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "删除workshop文件", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/ugc": { "delete": { "description": "删除UGC模组文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "删除UGC模组文件", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true }, { "type": "string", "description": "WorkshopID", "name": "workshopId", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/ugc/acf": { "get": { "description": "获取UGC模组的ACF文件信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取UGC mod acf文件信息", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/{modId}": { "get": { "description": "根据modId获取模组详细信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取mod信息", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "put": { "description": "根据modId更新模组", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "更新模组", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "delete": { "description": "根据modId删除模组", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "删除模组", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/player/log": { "get": { "description": "分页查询玩家日志", "tags": [ "playerLog" ], "summary": "分页查询玩家日志", "parameters": [ { "type": "string", "description": "玩家名称", "name": "name", "in": "query" }, { "type": "string", "description": "KuId", "name": "kuId", "in": "query" }, { "type": "string", "description": "SteamId", "name": "steamId", "in": "query" }, { "type": "string", "description": "角色", "name": "role", "in": "query" }, { "type": "string", "description": "操作", "name": "action", "in": "query" }, { "type": "string", "description": "IP地址", "name": "ip", "in": "query" }, { "type": "integer", "default": 1, "description": "页码", "name": "page", "in": "query" }, { "type": "integer", "default": 10, "description": "每页数量", "name": "size", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/player/log/delete": { "post": { "description": "删除玩家日志", "tags": [ "playerLog" ], "summary": "删除玩家日志", "parameters": [ { "description": "ID列表", "name": "ids", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "integer" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/player/log/delete/all": { "get": { "description": "删除所有玩家", "tags": [ "playerLog" ], "summary": "删除所有玩家日志", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/changePassword": { "post": { "description": "修改密码", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "修改密码", "parameters": [ { "description": "新密码", "name": "password", "in": "body", "required": true, "schema": { "type": "object" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/info": { "get": { "description": "获取用户信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "获取用户信息", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/login.UserInfo" } } } ] } } } } }, "/api/user/login": { "post": { "description": "用户登录", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "用户登录", "parameters": [ { "description": "用户信息", "name": "user", "in": "body", "required": true, "schema": { "$ref": "#/definitions/login.UserInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/logout": { "get": { "description": "用户登出", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "用户登出", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/update": { "post": { "description": "更新用户信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "更新用户信息", "parameters": [ { "description": "用户信息", "name": "user", "in": "body", "required": true, "schema": { "type": "object" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/backup/restore": { "get": { "description": "从备份文件恢复游戏存档", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "恢复备份", "parameters": [ { "type": "string", "description": "备份文件名", "name": "backupName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } } }, "definitions": { "dstConfig.DstConfig": { "type": "object", "properties": { "backup": { "type": "string" }, "beta": { "type": "integer" }, "bin": { "type": "integer" }, "cluster": { "type": "string" }, "conf_dir": { "description": "存档相对位置", "type": "string" }, "donot_starve_server_directory": { "type": "string" }, "force_install_dir": { "type": "string" }, "mod_download_path": { "type": "string" }, "persistent_storage_root": { "description": "根目录位置", "type": "string" }, "steamcmd": { "type": "string" }, "ugc_directory": { "type": "string" } } }, "game.DstPsAux": { "type": "object", "properties": { "RSS": { "type": "string" }, "VSZ": { "type": "string" }, "cpuUage": { "type": "string" }, "memUage": { "type": "string" } } }, "gameConfig.ClusterIni": { "type": "object", "properties": { "bind_ip": { "type": "string" }, "cluster_description": { "type": "string" }, "cluster_intention": { "type": "string" }, "cluster_key": { "type": "string" }, "cluster_language": { "type": "string" }, "cluster_name": { "type": "string" }, "cluster_password": { "type": "string" }, "console_enabled": { "description": "[MISC]", "type": "boolean" }, "game_mode": { "description": "[GAEMPLAY]", "type": "string" }, "lan_only_cluster": { "description": "[NETWORK]", "type": "boolean" }, "master_ip": { "type": "string" }, "master_port": { "type": "integer" }, "max_players": { "type": "integer" }, "max_snapshots": { "type": "integer" }, "offline_cluster": { "type": "boolean" }, "pause_when_nobody": { "type": "boolean" }, "pvp": { "type": "boolean" }, "shard_enabled": { "description": "[SHARD]", "type": "boolean" }, "steam_group_admins": { "type": "boolean" }, "steam_group_id": { "description": "[STEAM]", "type": "string" }, "steam_group_only": { "type": "boolean" }, "tick_rate": { "type": "integer" }, "vote_enabled": { "type": "boolean" }, "vote_kick_enabled": { "type": "boolean" }, "whitelist_slots": { "type": "integer" } } }, "gameConfig.ClusterIniConfig": { "type": "object", "properties": { "cluster": { "$ref": "#/definitions/gameConfig.ClusterIni" }, "token": { "type": "string" } } }, "gameConfig.HomeConfigVO": { "type": "object", "properties": { "cavesMapData": { "type": "string" }, "clusterDescription": { "type": "string" }, "clusterIntention": { "type": "string" }, "clusterName": { "type": "string" }, "clusterPassword": { "type": "string" }, "gameMode": { "type": "string" }, "masterMapData": { "type": "string" }, "maxPlayers": { "type": "integer" }, "max_snapshots": { "type": "integer" }, "modData": { "type": "string" }, "pause_when_nobody": { "type": "boolean" }, "pvp": { "type": "boolean" }, "token": { "type": "string" }, "type": { "type": "integer" }, "vote_enabled": { "type": "boolean" } } }, "handler.LevelStatus": { "type": "object", "properties": { "Ps": { "$ref": "#/definitions/game.DstPsAux" }, "isMaster": { "type": "boolean" }, "levelName": { "type": "string" }, "leveldataoverride": { "type": "string" }, "modoverrides": { "type": "string" }, "runVersion": { "type": "integer" }, "serverIni": { "$ref": "#/definitions/levelConfig.ServerIni" }, "status": { "type": "boolean" }, "uuid": { "type": "string" } } }, "levelConfig.LevelInfo": { "type": "object", "properties": { "isMaster": { "type": "boolean" }, "levelName": { "type": "string" }, "leveldataoverride": { "type": "string" }, "modoverrides": { "type": "string" }, "runVersion": { "type": "integer" }, "server_ini": { "$ref": "#/definitions/levelConfig.ServerIni" }, "uuid": { "type": "string" } } }, "levelConfig.ServerIni": { "type": "object", "properties": { "authentication_port": { "description": "[STEAM]", "type": "integer" }, "encode_user_path": { "description": "[ACCOUNT]", "type": "boolean" }, "id": { "type": "integer" }, "is_master": { "description": "[SHARD]", "type": "boolean" }, "master_server_port": { "type": "integer" }, "name": { "type": "string" }, "server_port": { "description": "[NETWORK]", "type": "integer" } } }, "login.UserInfo": { "type": "object", "properties": { "displayName": { "type": "string" }, "password": { "type": "string" }, "photoURL": { "type": "string" }, "username": { "type": "string" } } }, "mod.ModInfo": { "type": "object", "properties": { "author": { "type": "string" }, "child": { "type": "array", "items": { "type": "string" } }, "consumer_appid": { "type": "number" }, "creator_appid": { "type": "number" }, "desc": { "type": "string" }, "file_url": { "type": "string" }, "id": { "type": "string" }, "img": { "type": "string" }, "last_time": { "type": "number" }, "name": { "type": "string" }, "sub": { "type": "integer" }, "time": { "type": "integer" }, "v": { "type": "string" }, "vote": { "type": "object", "properties": { "num": { "type": "integer" }, "star": { "type": "integer" } } } } }, "model.BackupSnapshot": { "type": "object" }, "response.Response": { "type": "object", "properties": { "code": { "description": "提示代码", "type": "integer" }, "data": { "description": "数据" }, "msg": { "description": "提示信息", "type": "string" } } } }, "securityDefinitions": { "BearerAuth": { "description": "Type \"Bearer\" followed by a space and JWT token.", "type": "apiKey", "name": "Authorization", "in": "header" } } }` // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = &swag.Spec{ Version: "1.0", Host: "localhost:8082", BasePath: "/", Schemes: []string{}, Title: "DST Admin Go API", Description: "饥荒联机版服务器管理后台 API 文档", InfoInstanceName: "swagger", SwaggerTemplate: docTemplate, LeftDelim: "{{", RightDelim: "}}", } func init() { swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) } ================================================ FILE: docs/swagger.json ================================================ { "swagger": "2.0", "info": { "description": "饥荒联机版服务器管理后台 API 文档", "title": "DST Admin Go API", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "API Support", "url": "https://github.com/carrot-hu23/dst-admin-go" }, "license": { "name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" }, "version": "1.0" }, "host": "localhost:8082", "basePath": "/", "paths": { "/api/cluster/level": { "get": { "description": "获取指定世界的详细信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "获取单个世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "put": { "description": "批量更新多个世界的配置信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "批量更新世界", "parameters": [ { "description": "世界配置信息列表", "name": "levels", "in": "body", "required": true, "schema": { "type": "array", "items": { "$ref": "#/definitions/levelConfig.LevelInfo" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "创建一个新的世界(等级)", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "创建世界", "parameters": [ { "description": "世界配置信息", "name": "level", "in": "body", "required": true, "schema": { "$ref": "#/definitions/levelConfig.LevelInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "delete": { "description": "删除指定的世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "level" ], "summary": "删除世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/gen": { "get": { "description": "生成地图", "tags": [ "dstMap" ], "summary": "生成地图", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/has/walrusHut/plains": { "get": { "description": "检测地图中是否有walrusHutPlains", "tags": [ "dstMap" ], "summary": "检测地图中是否有walrusHutPlains", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/image": { "get": { "description": "获取地图图片", "tags": [ "dstMap" ], "summary": "获取地图图片", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/player/session/file": { "get": { "description": "获取玩家存档文件", "tags": [ "dstMap" ], "summary": "获取玩家存档文件", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/dst/map/session/file": { "get": { "description": "获取存档文件", "tags": [ "dstMap" ], "summary": "获取存档文件", "parameters": [ { "type": "string", "description": "levelName", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } }, "400": { "description": "Bad Request", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/8level/status": { "get": { "description": "获取所有世界的运行状态信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "获取服务器状态", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/definitions/handler.LevelStatus" } } } } ] } } } } }, "/api/game/archive": { "get": { "description": "获取当前集群的游戏存档列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "获取游戏存档列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup": { "get": { "description": "获取当前集群的所有备份文件列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "获取备份列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "put": { "description": "重命名指定的备份文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "重命名备份", "parameters": [ { "description": "请求体", "name": "request", "in": "body", "required": true, "schema": { "type": "object" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "创建新的游戏存档备份", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "创建备份", "parameters": [ { "type": "string", "description": "备份名称", "name": "backupName", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "delete": { "description": "删除指定的备份文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "删除备份", "parameters": [ { "description": "要删除的文件名列表", "name": "fileNames", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/download": { "get": { "description": "下载指定的备份文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "下载备份", "parameters": [ { "type": "string", "description": "备份文件名", "name": "backupName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/snapshot/list": { "get": { "description": "获取当前集群的所有快照备份列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "获取快照列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/snapshot/setting": { "get": { "description": "获取自动快照备份的设置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "获取快照设置", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "保存自动快照备份的设置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "保存快照设置", "parameters": [ { "description": "快照设置", "name": "setting", "in": "body", "required": true, "schema": { "$ref": "#/definitions/model.BackupSnapshot" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/backup/upload": { "post": { "description": "上传新的备份文件", "consumes": [ "multipart/form-data" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "上传备份", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/command": { "post": { "description": "运行命令", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "运行命令", "parameters": [ { "type": "string", "description": "命令", "name": "command", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config": { "get": { "description": "获取房间配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/gameConfig.HomeConfigVO" } } } ] } } } } }, "/api/game/config/adminlist": { "get": { "description": "获取房间 adminlist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 adminlist.txt 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } }, "post": { "description": "保存房间 adminlist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 adminlist.txt 配置", "parameters": [ { "description": "adminlist.txt 配置", "name": "list", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config/blacklist": { "get": { "description": "获取房间 blacklist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 blacklist.txt 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } }, "post": { "description": "保存房间 blacklist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 blacklist.txt 配置", "parameters": [ { "description": "blacklist.txt 配置", "name": "list", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config/clusterIni": { "get": { "description": "获取房间 cluster.ini 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 cluster.ini 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/gameConfig.ClusterIniConfig" } } } ] } } } }, "post": { "description": "保存房间 cluster.ini 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 cluster.ini 配置", "parameters": [ { "description": "cluster.ini 配置", "name": "config", "in": "body", "required": true, "schema": { "$ref": "#/definitions/gameConfig.ClusterIniConfig" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/config/whitelist": { "get": { "description": "获取房间 whitelist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "获取房间 whitelist.txt 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } }, "post": { "description": "保存房间 whitelist.txt 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "gameConfig" ], "summary": "保存房间 whitelist.txt 配置", "parameters": [ { "description": "whitelist.txt 配置", "name": "list", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/dst/config": { "get": { "description": "获取房间 dst 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "dstConfig" ], "summary": "获取房间 dst 配置", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/dstConfig.DstConfig" } } } ] } } } }, "post": { "description": "保存房间 dst 配置", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "dstConfig" ], "summary": "保存房间 dst 配置", "parameters": [ { "description": "dst 配置", "name": "config", "in": "body", "required": true, "schema": { "$ref": "#/definitions/dstConfig.DstConfig" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/level/server/download": { "get": { "description": "下载指定世界的完整服务器日志文件", "produces": [ "application/octet-stream" ], "tags": [ "log" ], "summary": "下载服务器日志", "parameters": [ { "type": "string", "description": "集群名称", "name": "clusterName", "in": "query" }, { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "服务器日志文件", "schema": { "type": "file" } } } } }, "/api/game/level/server/log": { "get": { "description": "获取指定世界的服务器日志(默认最近100行)", "produces": [ "application/json" ], "tags": [ "log" ], "summary": "获取服务器日志", "parameters": [ { "type": "string", "description": "集群名称", "name": "clusterName", "in": "query" }, { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true }, { "type": "string", "description": "返回日志行数,默认为100", "name": "lines", "in": "query" } ], "responses": { "200": { "description": "服务器日志列表", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "string" } } } } ] } } } } }, "/api/game/log/stream": { "get": { "description": "获取指定世界的实时日志流 (SSE)", "consumes": [ "text/event-stream" ], "produces": [ "text/event-stream" ], "tags": [ "log" ], "summary": "服务器日志流", "parameters": [ { "type": "string", "description": "集群名称", "name": "clusterName", "in": "query" }, { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "SSE 格式的日志流", "schema": { "type": "string" } } } } }, "/api/game/start": { "get": { "description": "启动世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "启动世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/start/all": { "get": { "description": "启动所有世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "启动所有世界", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/stop": { "get": { "description": "停止世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "停止世界", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/stop/all": { "get": { "description": "停止所有世界", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "game" ], "summary": "停止所有世界", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/game/system/info/stream": { "get": { "description": "获取服务器系统信息的实时流 (SSE)", "consumes": [ "text/event-stream" ], "produces": [ "text/event-stream" ], "tags": [ "game" ], "summary": "系统信息流", "responses": { "200": { "description": "SSE 格式的系统信息流", "schema": { "type": "string" } } } } }, "/api/game/update": { "get": { "description": "更新游戏", "tags": [ "update" ], "summary": "更新游戏", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/init": { "get": { "description": "检查系统是否进行了首次初始化", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "检查是否首次初始化", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "初始化系统首次用户信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "初始化首次用户", "parameters": [ { "description": "用户信息", "name": "userInfo", "in": "body", "required": true, "schema": { "$ref": "#/definitions/login.UserInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/kv": { "get": { "description": "获取kv值", "tags": [ "kv" ], "summary": "获取kv值", "parameters": [ { "type": "string", "description": "key", "name": "key", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "保存kv值", "tags": [ "kv" ], "summary": "保存kv值", "parameters": [ { "type": "string", "description": "key", "name": "key", "in": "formData", "required": true }, { "type": "string", "description": "value", "name": "value", "in": "formData", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod": { "get": { "description": "获取已订阅的模组列表", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取我的mod列表", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/modinfo": { "put": { "description": "批量更新所有已订阅模组的信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "批量更新模组信息", "parameters": [ { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "post": { "description": "保存模组配置信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "保存模组配置文件", "parameters": [ { "description": "模组信息", "name": "data", "in": "body", "required": true, "schema": { "$ref": "#/definitions/mod.ModInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/mod.ModInfo" } } } ] } } } } }, "/api/mod/modinfo/file": { "post": { "description": "手动添加模组配置文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "手动添加模组", "parameters": [ { "description": "模组信息", "name": "data", "in": "body", "required": true, "schema": { "type": "object" } }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/modinfo/{modId}": { "get": { "description": "根据modId获取模组配置文件内容", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取模组配置文件", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/mod.ModInfo" } } } ] } } } } }, "/api/mod/search": { "get": { "description": "搜索Steam创意工坊中的模组", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "搜索mod列表", "parameters": [ { "type": "string", "description": "搜索关键词", "name": "text", "in": "query" }, { "type": "integer", "default": 1, "description": "页码", "name": "page", "in": "query" }, { "type": "integer", "default": 10, "description": "每页数量", "name": "size", "in": "query" }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/setup/workshop": { "delete": { "description": "删除所有workshop模组文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "删除workshop文件", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/ugc": { "delete": { "description": "删除UGC模组文件", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "删除UGC模组文件", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true }, { "type": "string", "description": "WorkshopID", "name": "workshopId", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/ugc/acf": { "get": { "description": "获取UGC模组的ACF文件信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取UGC mod acf文件信息", "parameters": [ { "type": "string", "description": "世界名称", "name": "levelName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/mod/{modId}": { "get": { "description": "根据modId获取模组详细信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "获取mod信息", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "put": { "description": "根据modId更新模组", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "更新模组", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true }, { "type": "string", "default": "zh", "description": "语言", "name": "lang", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } }, "delete": { "description": "根据modId删除模组", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "mod" ], "summary": "删除模组", "parameters": [ { "type": "string", "description": "模组ID", "name": "modId", "in": "path", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/player/log": { "get": { "description": "分页查询玩家日志", "tags": [ "playerLog" ], "summary": "分页查询玩家日志", "parameters": [ { "type": "string", "description": "玩家名称", "name": "name", "in": "query" }, { "type": "string", "description": "KuId", "name": "kuId", "in": "query" }, { "type": "string", "description": "SteamId", "name": "steamId", "in": "query" }, { "type": "string", "description": "角色", "name": "role", "in": "query" }, { "type": "string", "description": "操作", "name": "action", "in": "query" }, { "type": "string", "description": "IP地址", "name": "ip", "in": "query" }, { "type": "integer", "default": 1, "description": "页码", "name": "page", "in": "query" }, { "type": "integer", "default": 10, "description": "每页数量", "name": "size", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/player/log/delete": { "post": { "description": "删除玩家日志", "tags": [ "playerLog" ], "summary": "删除玩家日志", "parameters": [ { "description": "ID列表", "name": "ids", "in": "body", "required": true, "schema": { "type": "array", "items": { "type": "integer" } } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/player/log/delete/all": { "get": { "description": "删除所有玩家", "tags": [ "playerLog" ], "summary": "删除所有玩家日志", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/changePassword": { "post": { "description": "修改密码", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "修改密码", "parameters": [ { "description": "新密码", "name": "password", "in": "body", "required": true, "schema": { "type": "object" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/info": { "get": { "description": "获取用户信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "获取用户信息", "responses": { "200": { "description": "OK", "schema": { "allOf": [ { "$ref": "#/definitions/response.Response" }, { "type": "object", "properties": { "data": { "$ref": "#/definitions/login.UserInfo" } } } ] } } } } }, "/api/user/login": { "post": { "description": "用户登录", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "用户登录", "parameters": [ { "description": "用户信息", "name": "user", "in": "body", "required": true, "schema": { "$ref": "#/definitions/login.UserInfo" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/logout": { "get": { "description": "用户登出", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "用户登出", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/api/user/update": { "post": { "description": "更新用户信息", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "user" ], "summary": "更新用户信息", "parameters": [ { "description": "用户信息", "name": "user", "in": "body", "required": true, "schema": { "type": "object" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } }, "/backup/restore": { "get": { "description": "从备份文件恢复游戏存档", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "backup" ], "summary": "恢复备份", "parameters": [ { "type": "string", "description": "备份文件名", "name": "backupName", "in": "query", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/response.Response" } } } } } }, "definitions": { "dstConfig.DstConfig": { "type": "object", "properties": { "backup": { "type": "string" }, "beta": { "type": "integer" }, "bin": { "type": "integer" }, "cluster": { "type": "string" }, "conf_dir": { "description": "存档相对位置", "type": "string" }, "donot_starve_server_directory": { "type": "string" }, "force_install_dir": { "type": "string" }, "mod_download_path": { "type": "string" }, "persistent_storage_root": { "description": "根目录位置", "type": "string" }, "steamcmd": { "type": "string" }, "ugc_directory": { "type": "string" } } }, "game.DstPsAux": { "type": "object", "properties": { "RSS": { "type": "string" }, "VSZ": { "type": "string" }, "cpuUage": { "type": "string" }, "memUage": { "type": "string" } } }, "gameConfig.ClusterIni": { "type": "object", "properties": { "bind_ip": { "type": "string" }, "cluster_description": { "type": "string" }, "cluster_intention": { "type": "string" }, "cluster_key": { "type": "string" }, "cluster_language": { "type": "string" }, "cluster_name": { "type": "string" }, "cluster_password": { "type": "string" }, "console_enabled": { "description": "[MISC]", "type": "boolean" }, "game_mode": { "description": "[GAEMPLAY]", "type": "string" }, "lan_only_cluster": { "description": "[NETWORK]", "type": "boolean" }, "master_ip": { "type": "string" }, "master_port": { "type": "integer" }, "max_players": { "type": "integer" }, "max_snapshots": { "type": "integer" }, "offline_cluster": { "type": "boolean" }, "pause_when_nobody": { "type": "boolean" }, "pvp": { "type": "boolean" }, "shard_enabled": { "description": "[SHARD]", "type": "boolean" }, "steam_group_admins": { "type": "boolean" }, "steam_group_id": { "description": "[STEAM]", "type": "string" }, "steam_group_only": { "type": "boolean" }, "tick_rate": { "type": "integer" }, "vote_enabled": { "type": "boolean" }, "vote_kick_enabled": { "type": "boolean" }, "whitelist_slots": { "type": "integer" } } }, "gameConfig.ClusterIniConfig": { "type": "object", "properties": { "cluster": { "$ref": "#/definitions/gameConfig.ClusterIni" }, "token": { "type": "string" } } }, "gameConfig.HomeConfigVO": { "type": "object", "properties": { "cavesMapData": { "type": "string" }, "clusterDescription": { "type": "string" }, "clusterIntention": { "type": "string" }, "clusterName": { "type": "string" }, "clusterPassword": { "type": "string" }, "gameMode": { "type": "string" }, "masterMapData": { "type": "string" }, "maxPlayers": { "type": "integer" }, "max_snapshots": { "type": "integer" }, "modData": { "type": "string" }, "pause_when_nobody": { "type": "boolean" }, "pvp": { "type": "boolean" }, "token": { "type": "string" }, "type": { "type": "integer" }, "vote_enabled": { "type": "boolean" } } }, "handler.LevelStatus": { "type": "object", "properties": { "Ps": { "$ref": "#/definitions/game.DstPsAux" }, "isMaster": { "type": "boolean" }, "levelName": { "type": "string" }, "leveldataoverride": { "type": "string" }, "modoverrides": { "type": "string" }, "runVersion": { "type": "integer" }, "serverIni": { "$ref": "#/definitions/levelConfig.ServerIni" }, "status": { "type": "boolean" }, "uuid": { "type": "string" } } }, "levelConfig.LevelInfo": { "type": "object", "properties": { "isMaster": { "type": "boolean" }, "levelName": { "type": "string" }, "leveldataoverride": { "type": "string" }, "modoverrides": { "type": "string" }, "runVersion": { "type": "integer" }, "server_ini": { "$ref": "#/definitions/levelConfig.ServerIni" }, "uuid": { "type": "string" } } }, "levelConfig.ServerIni": { "type": "object", "properties": { "authentication_port": { "description": "[STEAM]", "type": "integer" }, "encode_user_path": { "description": "[ACCOUNT]", "type": "boolean" }, "id": { "type": "integer" }, "is_master": { "description": "[SHARD]", "type": "boolean" }, "master_server_port": { "type": "integer" }, "name": { "type": "string" }, "server_port": { "description": "[NETWORK]", "type": "integer" } } }, "login.UserInfo": { "type": "object", "properties": { "displayName": { "type": "string" }, "password": { "type": "string" }, "photoURL": { "type": "string" }, "username": { "type": "string" } } }, "mod.ModInfo": { "type": "object", "properties": { "author": { "type": "string" }, "child": { "type": "array", "items": { "type": "string" } }, "consumer_appid": { "type": "number" }, "creator_appid": { "type": "number" }, "desc": { "type": "string" }, "file_url": { "type": "string" }, "id": { "type": "string" }, "img": { "type": "string" }, "last_time": { "type": "number" }, "name": { "type": "string" }, "sub": { "type": "integer" }, "time": { "type": "integer" }, "v": { "type": "string" }, "vote": { "type": "object", "properties": { "num": { "type": "integer" }, "star": { "type": "integer" } } } } }, "model.BackupSnapshot": { "type": "object" }, "response.Response": { "type": "object", "properties": { "code": { "description": "提示代码", "type": "integer" }, "data": { "description": "数据" }, "msg": { "description": "提示信息", "type": "string" } } } }, "securityDefinitions": { "BearerAuth": { "description": "Type \"Bearer\" followed by a space and JWT token.", "type": "apiKey", "name": "Authorization", "in": "header" } } } ================================================ FILE: docs/swagger.yaml ================================================ basePath: / definitions: dstConfig.DstConfig: properties: backup: type: string beta: type: integer bin: type: integer cluster: type: string conf_dir: description: 存档相对位置 type: string donot_starve_server_directory: type: string force_install_dir: type: string mod_download_path: type: string persistent_storage_root: description: 根目录位置 type: string steamcmd: type: string ugc_directory: type: string type: object game.DstPsAux: properties: RSS: type: string VSZ: type: string cpuUage: type: string memUage: type: string type: object gameConfig.ClusterIni: properties: bind_ip: type: string cluster_description: type: string cluster_intention: type: string cluster_key: type: string cluster_language: type: string cluster_name: type: string cluster_password: type: string console_enabled: description: '[MISC]' type: boolean game_mode: description: '[GAEMPLAY]' type: string lan_only_cluster: description: '[NETWORK]' type: boolean master_ip: type: string master_port: type: integer max_players: type: integer max_snapshots: type: integer offline_cluster: type: boolean pause_when_nobody: type: boolean pvp: type: boolean shard_enabled: description: '[SHARD]' type: boolean steam_group_admins: type: boolean steam_group_id: description: '[STEAM]' type: string steam_group_only: type: boolean tick_rate: type: integer vote_enabled: type: boolean vote_kick_enabled: type: boolean whitelist_slots: type: integer type: object gameConfig.ClusterIniConfig: properties: cluster: $ref: '#/definitions/gameConfig.ClusterIni' token: type: string type: object gameConfig.HomeConfigVO: properties: cavesMapData: type: string clusterDescription: type: string clusterIntention: type: string clusterName: type: string clusterPassword: type: string gameMode: type: string masterMapData: type: string max_snapshots: type: integer maxPlayers: type: integer modData: type: string pause_when_nobody: type: boolean pvp: type: boolean token: type: string type: type: integer vote_enabled: type: boolean type: object handler.LevelStatus: properties: Ps: $ref: '#/definitions/game.DstPsAux' isMaster: type: boolean levelName: type: string leveldataoverride: type: string modoverrides: type: string runVersion: type: integer serverIni: $ref: '#/definitions/levelConfig.ServerIni' status: type: boolean uuid: type: string type: object levelConfig.LevelInfo: properties: isMaster: type: boolean levelName: type: string leveldataoverride: type: string modoverrides: type: string runVersion: type: integer server_ini: $ref: '#/definitions/levelConfig.ServerIni' uuid: type: string type: object levelConfig.ServerIni: properties: authentication_port: description: '[STEAM]' type: integer encode_user_path: description: '[ACCOUNT]' type: boolean id: type: integer is_master: description: '[SHARD]' type: boolean master_server_port: type: integer name: type: string server_port: description: '[NETWORK]' type: integer type: object login.UserInfo: properties: displayName: type: string password: type: string photoURL: type: string username: type: string type: object mod.ModInfo: properties: author: type: string child: items: type: string type: array consumer_appid: type: number creator_appid: type: number desc: type: string file_url: type: string id: type: string img: type: string last_time: type: number name: type: string sub: type: integer time: type: integer v: type: string vote: properties: num: type: integer star: type: integer type: object type: object model.BackupSnapshot: type: object response.Response: properties: code: description: 提示代码 type: integer data: description: 数据 msg: description: 提示信息 type: string type: object host: localhost:8082 info: contact: name: API Support url: https://github.com/carrot-hu23/dst-admin-go description: 饥荒联机版服务器管理后台 API 文档 license: name: Apache 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html termsOfService: http://swagger.io/terms/ title: DST Admin Go API version: "1.0" paths: /api/cluster/level: delete: consumes: - application/json description: 删除指定的世界 parameters: - description: 世界名称 in: query name: levelName required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 删除世界 tags: - level get: consumes: - application/json description: 获取指定世界的详细信息 parameters: - description: 世界名称 in: query name: levelName required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取单个世界 tags: - level post: consumes: - application/json description: 创建一个新的世界(等级) parameters: - description: 世界配置信息 in: body name: level required: true schema: $ref: '#/definitions/levelConfig.LevelInfo' produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 创建世界 tags: - level put: consumes: - application/json description: 批量更新多个世界的配置信息 parameters: - description: 世界配置信息列表 in: body name: levels required: true schema: items: $ref: '#/definitions/levelConfig.LevelInfo' type: array produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 批量更新世界 tags: - level /api/dst/map/gen: get: description: 生成地图 parameters: - description: levelName in: query name: levelName required: true type: string responses: "200": description: OK schema: $ref: '#/definitions/response.Response' "400": description: Bad Request schema: $ref: '#/definitions/response.Response' summary: 生成地图 tags: - dstMap /api/dst/map/has/walrusHut/plains: get: description: 检测地图中是否有walrusHutPlains parameters: - description: levelName in: query name: levelName required: true type: string responses: "200": description: OK schema: $ref: '#/definitions/response.Response' "400": description: Bad Request schema: $ref: '#/definitions/response.Response' summary: 检测地图中是否有walrusHutPlains tags: - dstMap /api/dst/map/image: get: description: 获取地图图片 parameters: - description: levelName in: query name: levelName required: true type: string responses: "200": description: OK schema: $ref: '#/definitions/response.Response' "400": description: Bad Request schema: $ref: '#/definitions/response.Response' summary: 获取地图图片 tags: - dstMap /api/dst/map/player/session/file: get: description: 获取玩家存档文件 parameters: - description: levelName in: query name: levelName required: true type: string responses: "200": description: OK schema: $ref: '#/definitions/response.Response' "400": description: Bad Request schema: $ref: '#/definitions/response.Response' summary: 获取玩家存档文件 tags: - dstMap /api/dst/map/session/file: get: description: 获取存档文件 parameters: - description: levelName in: query name: levelName required: true type: string responses: "200": description: OK schema: $ref: '#/definitions/response.Response' "400": description: Bad Request schema: $ref: '#/definitions/response.Response' summary: 获取存档文件 tags: - dstMap /api/game/8level/status: get: consumes: - application/json description: 获取所有世界的运行状态信息 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: items: $ref: '#/definitions/handler.LevelStatus' type: array type: object summary: 获取服务器状态 tags: - game /api/game/archive: get: consumes: - application/json description: 获取当前集群的游戏存档列表 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取游戏存档列表 tags: - game /api/game/backup: delete: consumes: - application/json description: 删除指定的备份文件 parameters: - description: 要删除的文件名列表 in: body name: fileNames required: true schema: items: type: string type: array produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 删除备份 tags: - backup get: consumes: - application/json description: 获取当前集群的所有备份文件列表 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取备份列表 tags: - backup post: consumes: - application/json description: 创建新的游戏存档备份 parameters: - description: 备份名称 in: query name: backupName type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 创建备份 tags: - backup put: consumes: - application/json description: 重命名指定的备份文件 parameters: - description: 请求体 in: body name: request required: true schema: type: object produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 重命名备份 tags: - backup /api/game/backup/download: get: consumes: - application/json description: 下载指定的备份文件 parameters: - description: 备份文件名 in: query name: backupName required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 下载备份 tags: - backup /api/game/backup/snapshot/list: get: consumes: - application/json description: 获取当前集群的所有快照备份列表 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取快照列表 tags: - backup /api/game/backup/snapshot/setting: get: consumes: - application/json description: 获取自动快照备份的设置 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取快照设置 tags: - backup post: consumes: - application/json description: 保存自动快照备份的设置 parameters: - description: 快照设置 in: body name: setting required: true schema: $ref: '#/definitions/model.BackupSnapshot' produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 保存快照设置 tags: - backup /api/game/backup/upload: post: consumes: - multipart/form-data description: 上传新的备份文件 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 上传备份 tags: - backup /api/game/command: post: consumes: - application/json description: 运行命令 parameters: - description: 命令 in: query name: command required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 运行命令 tags: - game /api/game/config: get: consumes: - application/json description: 获取房间配置 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: $ref: '#/definitions/gameConfig.HomeConfigVO' type: object summary: 获取房间配置 tags: - gameConfig /api/game/config/adminlist: get: consumes: - application/json description: 获取房间 adminlist.txt 配置 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: items: type: string type: array type: object summary: 获取房间 adminlist.txt 配置 tags: - gameConfig post: consumes: - application/json description: 保存房间 adminlist.txt 配置 parameters: - description: adminlist.txt 配置 in: body name: list required: true schema: items: type: string type: array produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 保存房间 adminlist.txt 配置 tags: - gameConfig /api/game/config/blacklist: get: consumes: - application/json description: 获取房间 blacklist.txt 配置 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: items: type: string type: array type: object summary: 获取房间 blacklist.txt 配置 tags: - gameConfig post: consumes: - application/json description: 保存房间 blacklist.txt 配置 parameters: - description: blacklist.txt 配置 in: body name: list required: true schema: items: type: string type: array produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 保存房间 blacklist.txt 配置 tags: - gameConfig /api/game/config/clusterIni: get: consumes: - application/json description: 获取房间 cluster.ini 配置 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: $ref: '#/definitions/gameConfig.ClusterIniConfig' type: object summary: 获取房间 cluster.ini 配置 tags: - gameConfig post: consumes: - application/json description: 保存房间 cluster.ini 配置 parameters: - description: cluster.ini 配置 in: body name: config required: true schema: $ref: '#/definitions/gameConfig.ClusterIniConfig' produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 保存房间 cluster.ini 配置 tags: - gameConfig /api/game/config/whitelist: get: consumes: - application/json description: 获取房间 whitelist.txt 配置 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: items: type: string type: array type: object summary: 获取房间 whitelist.txt 配置 tags: - gameConfig post: consumes: - application/json description: 保存房间 whitelist.txt 配置 parameters: - description: whitelist.txt 配置 in: body name: list required: true schema: items: type: string type: array produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 保存房间 whitelist.txt 配置 tags: - gameConfig /api/game/dst/config: get: consumes: - application/json description: 获取房间 dst 配置 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: $ref: '#/definitions/dstConfig.DstConfig' type: object summary: 获取房间 dst 配置 tags: - dstConfig post: consumes: - application/json description: 保存房间 dst 配置 parameters: - description: dst 配置 in: body name: config required: true schema: $ref: '#/definitions/dstConfig.DstConfig' produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 保存房间 dst 配置 tags: - dstConfig /api/game/level/server/download: get: description: 下载指定世界的完整服务器日志文件 parameters: - description: 集群名称 in: query name: clusterName type: string - description: 世界名称 in: query name: levelName required: true type: string produces: - application/octet-stream responses: "200": description: 服务器日志文件 schema: type: file summary: 下载服务器日志 tags: - log /api/game/level/server/log: get: description: 获取指定世界的服务器日志(默认最近100行) parameters: - description: 集群名称 in: query name: clusterName type: string - description: 世界名称 in: query name: levelName required: true type: string - description: 返回日志行数,默认为100 in: query name: lines type: string produces: - application/json responses: "200": description: 服务器日志列表 schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: items: type: string type: array type: object summary: 获取服务器日志 tags: - log /api/game/log/stream: get: consumes: - text/event-stream description: 获取指定世界的实时日志流 (SSE) parameters: - description: 集群名称 in: query name: clusterName type: string - description: 世界名称 in: query name: levelName required: true type: string produces: - text/event-stream responses: "200": description: SSE 格式的日志流 schema: type: string summary: 服务器日志流 tags: - log /api/game/start: get: consumes: - application/json description: 启动世界 parameters: - description: 世界名称 in: query name: levelName required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 启动世界 tags: - game /api/game/start/all: get: consumes: - application/json description: 启动所有世界 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 启动所有世界 tags: - game /api/game/stop: get: consumes: - application/json description: 停止世界 parameters: - description: 世界名称 in: query name: levelName required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 停止世界 tags: - game /api/game/stop/all: get: consumes: - application/json description: 停止所有世界 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 停止所有世界 tags: - game /api/game/system/info/stream: get: consumes: - text/event-stream description: 获取服务器系统信息的实时流 (SSE) produces: - text/event-stream responses: "200": description: SSE 格式的系统信息流 schema: type: string summary: 系统信息流 tags: - game /api/game/update: get: description: 更新游戏 responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 更新游戏 tags: - update /api/init: get: consumes: - application/json description: 检查系统是否进行了首次初始化 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 检查是否首次初始化 tags: - user post: consumes: - application/json description: 初始化系统首次用户信息 parameters: - description: 用户信息 in: body name: userInfo required: true schema: $ref: '#/definitions/login.UserInfo' produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 初始化首次用户 tags: - user /api/kv: get: description: 获取kv值 parameters: - description: key in: query name: key required: true type: string responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取kv值 tags: - kv post: description: 保存kv值 parameters: - description: key in: formData name: key required: true type: string - description: value in: formData name: value required: true type: string responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 保存kv值 tags: - kv /api/mod: get: consumes: - application/json description: 获取已订阅的模组列表 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取我的mod列表 tags: - mod /api/mod/{modId}: delete: consumes: - application/json description: 根据modId删除模组 parameters: - description: 模组ID in: path name: modId required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 删除模组 tags: - mod get: consumes: - application/json description: 根据modId获取模组详细信息 parameters: - description: 模组ID in: path name: modId required: true type: string - default: zh description: 语言 in: query name: lang type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取mod信息 tags: - mod put: consumes: - application/json description: 根据modId更新模组 parameters: - description: 模组ID in: path name: modId required: true type: string - default: zh description: 语言 in: query name: lang type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 更新模组 tags: - mod /api/mod/modinfo: post: consumes: - application/json description: 保存模组配置信息 parameters: - description: 模组信息 in: body name: data required: true schema: $ref: '#/definitions/mod.ModInfo' produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: $ref: '#/definitions/mod.ModInfo' type: object summary: 保存模组配置文件 tags: - mod put: consumes: - application/json description: 批量更新所有已订阅模组的信息 parameters: - default: zh description: 语言 in: query name: lang type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 批量更新模组信息 tags: - mod /api/mod/modinfo/{modId}: get: consumes: - application/json description: 根据modId获取模组配置文件内容 parameters: - description: 模组ID in: path name: modId required: true type: string produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: $ref: '#/definitions/mod.ModInfo' type: object summary: 获取模组配置文件 tags: - mod /api/mod/modinfo/file: post: consumes: - application/json description: 手动添加模组配置文件 parameters: - description: 模组信息 in: body name: data required: true schema: type: object - default: zh description: 语言 in: query name: lang type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 手动添加模组 tags: - mod /api/mod/search: get: consumes: - application/json description: 搜索Steam创意工坊中的模组 parameters: - description: 搜索关键词 in: query name: text type: string - default: 1 description: 页码 in: query name: page type: integer - default: 10 description: 每页数量 in: query name: size type: integer - default: zh description: 语言 in: query name: lang type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 搜索mod列表 tags: - mod /api/mod/setup/workshop: delete: consumes: - application/json description: 删除所有workshop模组文件 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 删除workshop文件 tags: - mod /api/mod/ugc: delete: consumes: - application/json description: 删除UGC模组文件 parameters: - description: 世界名称 in: query name: levelName required: true type: string - description: WorkshopID in: query name: workshopId required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 删除UGC模组文件 tags: - mod /api/mod/ugc/acf: get: consumes: - application/json description: 获取UGC模组的ACF文件信息 parameters: - description: 世界名称 in: query name: levelName required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 获取UGC mod acf文件信息 tags: - mod /api/player/log: get: description: 分页查询玩家日志 parameters: - description: 玩家名称 in: query name: name type: string - description: KuId in: query name: kuId type: string - description: SteamId in: query name: steamId type: string - description: 角色 in: query name: role type: string - description: 操作 in: query name: action type: string - description: IP地址 in: query name: ip type: string - default: 1 description: 页码 in: query name: page type: integer - default: 10 description: 每页数量 in: query name: size type: integer responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 分页查询玩家日志 tags: - playerLog /api/player/log/delete: post: description: 删除玩家日志 parameters: - description: ID列表 in: body name: ids required: true schema: items: type: integer type: array responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 删除玩家日志 tags: - playerLog /api/player/log/delete/all: get: description: 删除所有玩家 responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 删除所有玩家日志 tags: - playerLog /api/user/changePassword: post: consumes: - application/json description: 修改密码 parameters: - description: 新密码 in: body name: password required: true schema: type: object produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 修改密码 tags: - user /api/user/info: get: consumes: - application/json description: 获取用户信息 produces: - application/json responses: "200": description: OK schema: allOf: - $ref: '#/definitions/response.Response' - properties: data: $ref: '#/definitions/login.UserInfo' type: object summary: 获取用户信息 tags: - user /api/user/login: post: consumes: - application/json description: 用户登录 parameters: - description: 用户信息 in: body name: user required: true schema: $ref: '#/definitions/login.UserInfo' produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 用户登录 tags: - user /api/user/logout: get: consumes: - application/json description: 用户登出 produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 用户登出 tags: - user /api/user/update: post: consumes: - application/json description: 更新用户信息 parameters: - description: 用户信息 in: body name: user required: true schema: type: object produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 更新用户信息 tags: - user /backup/restore: get: consumes: - application/json description: 从备份文件恢复游戏存档 parameters: - description: 备份文件名 in: query name: backupName required: true type: string produces: - application/json responses: "200": description: OK schema: $ref: '#/definitions/response.Response' summary: 恢复备份 tags: - backup securityDefinitions: BearerAuth: description: Type "Bearer" followed by a space and JWT token. in: header name: Authorization type: apiKey swagger: "2.0" ================================================ FILE: go.mod ================================================ module dst-admin-go go 1.23.0 toolchain go1.24.7 require ( github.com/gin-contrib/sessions v1.0.1 github.com/gin-gonic/gin v1.10.0 github.com/glebarez/sqlite v1.8.0 github.com/go-ini/ini v1.67.0 github.com/hpcloud/tail v1.0.0 github.com/shirou/gopsutil v3.21.11+incompatible github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.1 github.com/swaggo/swag v1.16.6 github.com/yuin/gopher-lua v1.1.0 golang.org/x/text v0.23.0 gopkg.in/yaml.v3 v3.0.1 gorm.io/gorm v1.25.8 ) require ( github.com/KyleBanks/depth v1.2.1 // indirect github.com/PuerkitoBio/purell v1.1.1 // indirect github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/bytedance/sonic v1.11.6 // indirect github.com/bytedance/sonic/loader v0.1.1 // indirect github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/iasm v0.2.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/gzip v1.0.1 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/glebarez/go-sqlite v1.21.1 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.19.6 // indirect github.com/go-openapi/spec v0.20.4 // indirect github.com/go-openapi/swag v0.19.15 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.20.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/google/uuid v1.3.0 // indirect github.com/gorilla/context v1.1.2 // indirect github.com/gorilla/securecookie v1.1.2 // indirect github.com/gorilla/sessions v1.2.2 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mailru/easyjson v0.7.6 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/tklauser/go-sysconf v0.3.11 // indirect github.com/tklauser/numcpus v0.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect github.com/yusufpapurcu/wmi v1.2.2 // indirect golang.org/x/arch v0.8.0 // indirect golang.org/x/crypto v0.36.0 // indirect golang.org/x/mod v0.17.0 // indirect golang.org/x/net v0.38.0 // indirect golang.org/x/sys v0.31.0 // indirect golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect google.golang.org/protobuf v1.34.1 // indirect gopkg.in/fsnotify.v1 v1.4.7 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect modernc.org/libc v1.22.6 // indirect modernc.org/mathutil v1.5.0 // indirect modernc.org/memory v1.5.0 // indirect modernc.org/sqlite v1.22.1 // indirect ) ================================================ FILE: go.sum ================================================ github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gin-contrib/gzip v1.0.1 h1:HQ8ENHODeLY7a4g1Au/46Z92bdGFl74OhxcZble9WJE= github.com/gin-contrib/gzip v1.0.1/go.mod h1:njt428fdUNRvjuJf16tZMYZ2Yl+WQB53X5wmhDwXvC4= github.com/gin-contrib/sessions v1.0.1 h1:3hsJyNs7v7N8OtelFmYXFrulAf6zSR7nW/putcPEHxI= github.com/gin-contrib/sessions v1.0.1/go.mod h1:ouxSFM24/OgIud5MJYQJLpy6AwxQ5EYO9yLhbtObGkM= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= github.com/glebarez/go-sqlite v1.21.1 h1:7MZyUPh2XTrHS7xNEHQbrhfMZuPSzhkm2A1qgg0y5NY= github.com/glebarez/go-sqlite v1.21.1/go.mod h1:ISs8MF6yk5cL4n/43rSOmVMGJJjHYr7L2MbZZ5Q4E2E= github.com/glebarez/sqlite v1.8.0 h1:02X12E2I/4C1n+v90yTqrjRa8yuo7c3KeHI3FRznCvc= github.com/glebarez/sqlite v1.8.0/go.mod h1:bpET16h1za2KOOMb8+jCp6UBP/iahDpfPQqSaYLTLx8= github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o= github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM= github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY= github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= 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.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b h1:aUNXCGgukb4gtY99imuIeoh8Vr0GSwAlYxPAhqZrpFc= github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY= github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw= github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI= github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg= github.com/tklauser/go-sysconf v0.3.11 h1:89WgdJhk5SNwJfu+GKyYveZ4IaJ7xAkecBo+KdJV0CM= github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI= github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms= github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/gopher-lua v1.1.0 h1:BojcDhfyDWgU2f2TOzYK/g5p2gxMrku8oupLDqlnSqE= github.com/yuin/gopher-lua v1.1.0/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gorm.io/gorm v1.25.8 h1:WAGEZ/aEcznN4D03laj8DKnehe1e9gYQAjW8xyPRdeo= gorm.io/gorm v1.25.8/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= modernc.org/libc v1.22.6 h1:cbXU8R+A6aOjRuhsFh3nbDWXO/Hs4ClJRXYB11KmPDo= modernc.org/libc v1.22.6/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= modernc.org/sqlite v1.22.1 h1:P2+Dhp5FR1RlVRkQ3dDfCiv3Ok8XPxqpe70IjYVA9oE= modernc.org/sqlite v1.22.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk= nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= ================================================ FILE: internal/api/handler/backup_handler.go ================================================ package handler import ( "dst-admin-go/internal/database" "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/backup" "log" "net/http" "strings" "github.com/gin-gonic/gin" ) type BackupHandler struct { backupService *backup.BackupService } func NewBackupHandler(backupService *backup.BackupService) *BackupHandler { return &BackupHandler{ backupService: backupService, } } func (h *BackupHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/game/backup", h.GetBackupList) router.POST("/api/game/backup", h.CreateBackup) router.DELETE("/api/game/backup", h.DeleteBackup) router.PUT("/api/game/backup", h.RenameBackup) router.GET("/api/game/backup/download", h.DownloadBackup) router.POST("/api/game/backup/upload", h.UploadBackup) router.GET("/backup/restore", h.RestoreBackup) router.POST("/api/game/backup/snapshot/setting", h.SaveBackupSnapshotsSetting) router.GET("/api/game/backup/snapshot/setting", h.GetBackupSnapshotsSetting) router.GET("/api/game/backup/snapshot/list", h.BackupSnapshotsList) } // DeleteBackup 删除备份 // @Summary 删除备份 // @Description 删除指定的备份文件 // @Tags backup // @Accept json // @Produce json // @Param fileNames body []string true "要删除的文件名列表" // @Success 200 {object} response.Response // @Router /api/game/backup [delete] func (h *BackupHandler) DeleteBackup(ctx *gin.Context) { var body struct { FileNames []string `json:"fileNames"` } if err := ctx.BindJSON(&body); err != nil { return } h.backupService.DeleteBackup(ctx, body.FileNames) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "delete backups success", Data: nil, }) } // DownloadBackup 下载备份 // @Summary 下载备份 // @Description 下载指定的备份文件 // @Tags backup // @Accept json // @Produce json // @Param backupName query string true "备份文件名" // @Success 200 {object} response.Response // @Router /api/game/backup/download [get] func (h *BackupHandler) DownloadBackup(ctx *gin.Context) { h.backupService.DownloadBackup(ctx) } // GetBackupList 获取备份列表 // @Summary 获取备份列表 // @Description 获取当前集群的所有备份文件列表 // @Tags backup // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/game/backup [get] func (h *BackupHandler) GetBackupList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "get backup list success", Data: h.backupService.GetBackupList(clusterName), }) } // RenameBackup 重命名备份 // @Summary 重命名备份 // @Description 重命名指定的备份文件 // @Tags backup // @Accept json // @Produce json // @Param request body object true "请求体" schema-example({"fileName": "old_name", "newName": "new_name"}) // @Success 200 {object} response.Response // @Router /api/game/backup [put] func (h *BackupHandler) RenameBackup(ctx *gin.Context) { var body struct { FileName string `json:"fileName"` NewName string `json:"newName"` } if err := ctx.BindJSON(&body); err != nil { return } h.backupService.RenameBackup(ctx, body.FileName, body.NewName) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "rename backup success", Data: nil, }) } // RestoreBackup 恢复备份 // @Summary 恢复备份 // @Description 从备份文件恢复游戏存档 // @Tags backup // @Accept json // @Produce json // @Param backupName query string true "备份文件名" // @Success 200 {object} response.Response // @Router /backup/restore [get] func (h *BackupHandler) RestoreBackup(ctx *gin.Context) { backupName := ctx.Query("backupName") h.backupService.RestoreBackup(ctx, backupName) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "restore backup success", Data: nil, }) } // UploadBackup 上传备份 // @Summary 上传备份 // @Description 上传新的备份文件 // @Tags backup // @Accept multipart/form-data // @Produce json // @Success 200 {object} response.Response // @Router /api/game/backup/upload [post] func (h *BackupHandler) UploadBackup(ctx *gin.Context) { h.backupService.UploadBackup(ctx) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "upload backup success", Data: nil, }) } // CreateBackup 创建备份 // @Summary 创建备份 // @Description 创建新的游戏存档备份 // @Tags backup // @Accept json // @Produce json // @Param backupName query string false "备份名称" // @Success 200 {object} response.Response // @Router /api/game/backup [post] func (h *BackupHandler) CreateBackup(ctx *gin.Context) { var body struct { BackupName string `json:"backupName"` } if err := ctx.ShouldBind(&body); err != nil { body.BackupName = "" } clusterName := context.GetClusterName(ctx) h.backupService.CreateBackup(clusterName, body.BackupName) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "create backup success", Data: nil, }) } // SaveBackupSnapshotsSetting 保存快照设置 // @Summary 保存快照设置 // @Description 保存自动快照备份的设置 // @Tags backup // @Accept json // @Produce json // @Param setting body model.BackupSnapshot true "快照设置" // @Success 200 {object} response.Response // @Router /api/game/backup/snapshot/setting [post] func (h *BackupHandler) SaveBackupSnapshotsSetting(ctx *gin.Context) { var backupSnapshot model.BackupSnapshot var oldBackupSnapshot model.BackupSnapshot err := ctx.ShouldBind(&backupSnapshot) if err != nil { log.Panicln("参数错误", err) } db := database.Db db.First(&oldBackupSnapshot) oldBackupSnapshot.Enable = backupSnapshot.Enable oldBackupSnapshot.Interval = backupSnapshot.Interval oldBackupSnapshot.MaxSnapshots = backupSnapshot.MaxSnapshots oldBackupSnapshot.IsCSave = backupSnapshot.IsCSave db.Save(&oldBackupSnapshot) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: oldBackupSnapshot, }) } // GetBackupSnapshotsSetting 获取快照设置 // @Summary 获取快照设置 // @Description 获取自动快照备份的设置 // @Tags backup // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/game/backup/snapshot/setting [get] func (h *BackupHandler) GetBackupSnapshotsSetting(ctx *gin.Context) { var oldBackupSnapshot model.BackupSnapshot db := database.Db db.First(&oldBackupSnapshot) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: oldBackupSnapshot, }) } // BackupSnapshotsList 获取快照列表 // @Summary 获取快照列表 // @Description 获取当前集群的所有快照备份列表 // @Tags backup // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/game/backup/snapshot/list [get] func (h *BackupHandler) BackupSnapshotsList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var snapshotBackupList []backup.BackupInfo backupList := h.backupService.GetBackupList(clusterName) for i := range backupList { name := backupList[i].FileName if strings.HasPrefix(name, "(snapshot)") && strings.Contains(name, clusterName) { snapshotBackupList = append(snapshotBackupList, backupList[i]) } } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: snapshotBackupList, }) } ================================================ FILE: internal/api/handler/dst_api_handler.go ================================================ package handler import ( "bytes" "encoding/json" "fmt" "io" "log" "net/http" "net/url" "time" "github.com/gin-gonic/gin" ) type DstHomeDetailParam struct { RowId string `json:"rowId"` Region string `json:"region"` } func NewDstHomeDetailParam() *DstHomeDetailParam { return &DstHomeDetailParam{} } type DstHomeServerParam struct { Page int `json:"page"` Paginate int `json:"paginate"` SortType string `json:"sort_type"` SortWay int `json:"sort_way"` Search_type int `json:"search_type"` Search_content string `json:"search_content"` Mode string `json:"mode"` Mod int `json:"mod"` Season string `json:"season"` Pvp int `json:"pvp"` Password int `json:"password"` World int `json:"world"` Playerpercent string `json:"playerpercent"` } func NewDstHomeServerParam() *DstHomeServerParam { return &DstHomeServerParam{} } type DstApiHandler struct { } func NewDstApiHandler() *DstApiHandler { return &DstApiHandler{} } func (h *DstApiHandler) RegisterRoute(router *gin.RouterGroup) { router.POST("/api/dst/home/server", h.GetDstHomeServerList) router.POST("/api/dst/home/server/detail", h.GetDstHomeDetailList) router.GET("/api/dst/home/server2", h.GetDstHomeServerList2) router.GET("/api/dst/home/server/detail2", h.GetDstHomeDetailList2) // 配置路由 router.Any("/api/dst-static/*filepath", h.GiteeProxy) } // 获取第三方饥荒服务器 func (h *DstApiHandler) GetDstHomeServerList(c *gin.Context) { // response, err := http.Get("https://dst.liuyh.com/index/serverlist/getserverlist.html") // if err != nil || response.StatusCode != http.StatusOK { // c.Status(http.StatusServiceUnavailable) // return // } param := NewDstHomeServerParam() err := c.ShouldBind(param) if err != nil { log.Println("参数解析错误", err) } query_data := map[string]any{} query_data["page"] = param.Page query_data["paginate"] = param.Paginate query_data["sort_type"] = param.SortType query_data["sort_way"] = param.SortWay query_data["search_type"] = param.Search_type if param.Search_content != "" { query_data["search_content"] = param.Search_content } if param.Mode != "" { query_data["mode"] = param.Mode } if param.Season != "" { query_data["season"] = param.Season } if param.Pvp != -1 { query_data["pvp"] = param.Pvp } if param.Mod != -1 { query_data["mod"] = param.Mod } if param.Password != -1 { query_data["password"] = param.Password } if param.World != -1 { query_data["world"] = param.World } if param.Playerpercent != "" { query_data["playerpercent"] = param.Playerpercent } bytesData, err := json.Marshal(query_data) log.Println("param", string(bytesData)) if err != nil { log.Println("josn 解析异常") } b_reader := bytes.NewReader(bytesData) url := "http://dst.liuyh.com/index/serverlist/getserverlist.html" req, _ := http.NewRequest("POST", url, b_reader) // 比如说设置个token req.Header.Set("X-Requested-With", "XMLHttpRequest") req.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(req) if err != nil || response.StatusCode != http.StatusOK { c.Status(http.StatusServiceUnavailable) return } reader := response.Body contentLength := response.ContentLength contentType := response.Header.Get("Content-Type") extraHeaders := map[string]string{ //"Content-Disposition": `attachment; filename="gopher.png"`, "X-Requested-With": "XMLHttpRequest", } c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) } // 获取第三方饥荒服务器详情 func (h *DstApiHandler) GetDstHomeDetailList(c *gin.Context) { param := NewDstHomeDetailParam() err := c.ShouldBind(param) if err != nil { log.Println("参数解析错误", err) } bytesData, err := json.Marshal(param) if err != nil { log.Println("josn 解析异常") } b_reader := bytes.NewReader(bytesData) url := "http://dst.liuyh.com/index/serverlist/getserverdetail.html" req, _ := http.NewRequest("POST", url, b_reader) // 比如说设置个token req.Header.Set("X-Requested-With", "XMLHttpRequest") req.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(req) if err != nil || response.StatusCode != http.StatusOK { c.Status(http.StatusServiceUnavailable) return } reader := response.Body contentLength := response.ContentLength contentType := response.Header.Get("Content-Type") extraHeaders := map[string]string{ //"Content-Disposition": `attachment; filename="gopher.png"`, "X-Requested-With": "XMLHttpRequest", } c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) } func (h *DstApiHandler) GetDstHomeServerList2(ctx *gin.Context) { originalURL := "https://api.dstserverlist.top/api/list" u, err := url.Parse(originalURL) if err != nil { fmt.Println("Failed to parse URL:", err) return } // 构建参数 params := url.Values{} params.Add("page", ctx.DefaultQuery("current", "1")) params.Add("pageCount", ctx.DefaultQuery("pageSize", "10")) params.Add("name", ctx.Query("Name")) // 将参数编码为查询字符串 queryString := params.Encode() // 将查询字符串附加到原始URL u.RawQuery = queryString // 获取新的URL字符串 newURL := u.String() req, _ := http.NewRequest("POST", newURL, nil) // 比如说设置个token req.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(req) if err != nil || response.StatusCode != http.StatusOK { ctx.Status(http.StatusServiceUnavailable) return } reader := response.Body contentLength := response.ContentLength contentType := response.Header.Get("Content-Type") extraHeaders := map[string]string{ //"Content-Disposition": `attachment; filename="gopher.png"`, //"X-Requested-With": "XMLHttpRequest", } ctx.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) } func (h *DstApiHandler) GetDstHomeDetailList2(ctx *gin.Context) { originalURL := "https://api.dstserverlist.top/api/details/" + ctx.Query("rowId") req, _ := http.NewRequest("POST", originalURL, nil) // 比如说设置个token req.Header.Set("Content-Type", "application/json") response, err := (&http.Client{}).Do(req) if err != nil || response.StatusCode != http.StatusOK { ctx.Status(http.StatusServiceUnavailable) return } reader := response.Body contentLength := response.ContentLength contentType := response.Header.Get("Content-Type") extraHeaders := map[string]string{ //"Content-Disposition": `attachment; filename="gopher.png"`, //"X-Requested-With": "XMLHttpRequest", } ctx.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) } func (h *DstApiHandler) GiteeProxy(c *gin.Context) { // 获取路径参数 filePath := c.Param("filepath") // 处理路径前缀的斜杠(Gin 的路径参数会保留斜杠) if len(filePath) > 0 && filePath[0] == '/' { filePath = filePath[1:] } // 构建目标 URL targetURL := "https://gitee.com/hhhuhu23/dst-static/raw/master/" + filePath // 创建带超时的 HTTP 客户端 client := &http.Client{ Timeout: 10 * time.Second, } // 创建代理请求 req, err := http.NewRequest(c.Request.Method, targetURL, c.Request.Body) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{ "error": "Failed to create request", }) return } // 复制请求头 for key, values := range c.Request.Header { for _, value := range values { // 排除 Host 头,避免影响转发 if key == "Host" || key == "Referer" { continue } req.Header.Add(key, value) } } // 发送请求 resp, err := client.Do(req) if err != nil { c.AbortWithStatusJSON(http.StatusBadGateway, gin.H{ "error": "Failed to fetch resource", }) return } defer resp.Body.Close() // 设置 CORS 头 c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") c.Header("Access-Control-Allow-Headers", "Origin, Content-Type") // 复制响应头 for key, values := range resp.Header { for _, value := range values { c.Header(key, value) } } // 设置状态码 c.Status(resp.StatusCode) // 复制响应体 if _, err := io.Copy(c.Writer, resp.Body); err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{ "error": "Failed to stream response", }) } } ================================================ FILE: internal/api/handler/dst_config_handler.go ================================================ package handler import ( "dst-admin-go/internal/collect" "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/dstConfig" "net/http" "github.com/gin-gonic/gin" ) type DstConfigHandler struct { dstConfig dstConfig.Config archive *archive.PathResolver } func NewDstConfigHandler(dstConfig dstConfig.Config, archive *archive.PathResolver) *DstConfigHandler { return &DstConfigHandler{ dstConfig: dstConfig, archive: archive, } } func (h *DstConfigHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("api/dst/config", h.GetDstConfig) router.POST("api/dst/config", h.SaveDstConfig) } // GetDstConfig 获取房间 dst 配置 swagger 注释 // @Summary 获取房间 dst 配置 // @Description 获取房间 dst 配置 // @Tags dstConfig // @Accept json // @Produce json // @Success 200 {object} response.Response{data=dstConfig.DstConfig} // @Router /api/game/dst/config [get] func (h *DstConfigHandler) GetDstConfig(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) config, err := h.dstConfig.GetDstConfig(clusterName) if err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 500, Msg: "failed to get dst config: " + err.Error(), Data: nil, }) return } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: config, }) } // SaveDstConfig 保存房间 dst 配置 swagger 注释 // @Summary 保存房间 dst 配置 // @Description 保存房间 dst 配置 // @Tags dstConfig // @Accept json // @Produce json // @Param config body dstConfig.DstConfig true "dst 配置" // @Success 200 {object} response.Response // @Router /api/game/dst/config [post] func (h *DstConfigHandler) SaveDstConfig(ctx *gin.Context) { config := dstConfig.DstConfig{} if err := ctx.ShouldBindJSON(&config); err != nil { ctx.JSON(400, gin.H{"error": "Invalid request body"}) return } err := h.dstConfig.SaveDstConfig(context.GetClusterName(ctx), config) if err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 500, Msg: "failed to save dst config: " + err.Error(), Data: nil, }) return } clusterPath := h.archive.ClusterPath(config.Cluster) collect.Collector.ReCollect(clusterPath, config.Cluster) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "DstConfig saved successfully", Data: nil, }) } ================================================ FILE: internal/api/handler/dst_map_handler.go ================================================ package handler import ( "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/dstMap" "fmt" "io/ioutil" "log" "net/http" "os" "path/filepath" "strings" "time" "github.com/gin-gonic/gin" ) type DstMapHandler struct { generator *dstMap.DSTMapGenerator archiveResolver *archive.PathResolver } func NewDstMapHandler(archiveResolver *archive.PathResolver, generator *dstMap.DSTMapGenerator) *DstMapHandler { return &DstMapHandler{ archiveResolver: archiveResolver, generator: generator, } } func (d *DstMapHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/dst/map/gen", d.GenDstMap) router.GET("/api/dst/map/image", d.GetDstMapImage) router.GET("/api/dst/map/has/walrusHut/plains", d.HasWalrusHutPlains) router.GET("/api/dst/map/session/file", d.GetSessionFile) router.GET("/api/dst/map/player/session/file", d.GetPlayerSessionFile) } // GenDstMap 生成地图 生成 swagger 文档注释 // @Summary 生成地图 // @Description 生成地图 // @Tags dstMap // @Param levelName query string true "levelName" // @Success 200 {object} response.Response // @Failure 400 {object} response.Response // @Router /api/dst/map/gen [get] func (d *DstMapHandler) GenDstMap(ctx *gin.Context) { levelName := ctx.Query("levelName") if levelName == "" { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "levelName 参数不能为空", }) return } clusterName := context.GetClusterName(ctx) clusterPath := d.archiveResolver.ClusterPath(clusterName) outputImage := filepath.Join(clusterPath, "dst_map_"+levelName+".jpg") sessionPath := filepath.Join(clusterPath, levelName, "save", "session") filePath, err := findLatestMetaFile(sessionPath) if err != nil { log.Panicln(err) } log.Println("生成地图", filePath, outputImage) height, width, err := dstMap.ExtractDimensions(filePath) if err != nil { log.Panicln(err) } err = d.generator.GenerateMap( filePath, outputImage, height, width, ) if err != nil { log.Panicln(err) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: nil, }) } // GetDstMapImage 获取地图图片 获取 swagger 文档注释 // @Summary 获取地图图片 // @Description 获取地图图片 // @Tags dstMap // @Param levelName query string true "levelName" // @Success 200 {object} response.Response // @Failure 400 {object} response.Response // @Router /api/dst/map/image [get] func (d *DstMapHandler) GetDstMapImage(ctx *gin.Context) { levelName := ctx.Query("levelName") if levelName == "" { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "levelName 参数不能为空", }) return } clusterName := context.GetClusterName(ctx) clusterPath := d.archiveResolver.ClusterPath(clusterName) outputImage := filepath.Join(clusterPath, "dst_map_"+levelName+".jpg") log.Println(outputImage) // 使用 Gin 提供的文件传输方法返回图片 ctx.File(outputImage) ctx.Header("Content-Type", "image/png") } // HasWalrusHutPlains 检测地图中是否有walrusHutPlains 获取 swagger 文档注释 // @Summary 检测地图中是否有walrusHutPlains // @Description 检测地图中是否有walrusHutPlains // @Tags dstMap // @Param levelName query string true "levelName" // @Success 200 {object} response.Response // @Failure 400 {object} response.Response // @Router /api/dst/map/has/walrusHut/plains [get] func (d *DstMapHandler) HasWalrusHutPlains(ctx *gin.Context) { levelName := ctx.Query("levelName") if levelName == "" { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "levelName 参数不能为空", }) return } clusterName := context.GetClusterName(ctx) clusterPath := d.archiveResolver.ClusterPath(clusterName) sessionPath := filepath.Join(clusterPath, levelName, "save", "session") filePath, err := findLatestMetaFile(sessionPath) if err != nil { log.Panicln(err) } file, err := fileUtils.ReadFile(filePath) if err != nil { log.Panicln(err) } hasWalrusHutPlains := strings.Contains(file, "WalrusHut_Plains") ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: hasWalrusHutPlains, }) } // GetSessionFile 获取存档文件 获取 swagger 文档注释 // @Summary 获取存档文件 // @Description 获取存档文件 // @Tags dstMap // @Param levelName query string true "levelName" // @Success 200 {object} response.Response // @Failure 400 {object} response.Response // @Router /api/dst/map/session/file [get] func (d *DstMapHandler) GetSessionFile(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) clusterPath := d.archiveResolver.ClusterPath(clusterName) levelName := ctx.Query("levelName") if levelName == "" { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "levelName 参数不能为空", }) return } sessionPath := filepath.Join(clusterPath, levelName, "save", "session") filePath, err := findLatestMetaFile(sessionPath) if err != nil { log.Panicln(err) } file, err := fileUtils.ReadFile(filePath) if err != nil { log.Panicln(err) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: file, }) } // GetPlayerSessionFile 获取玩家存档文件 获取 swagger 文档 // @Summary 获取玩家存档文件 // @Description 获取玩家存档文件 // @Tags dstMap // @Param levelName query string true "levelName" // @Success 200 {object} response.Response // @Failure 400 {object} response.Response // @Router /api/dst/map/player/session/file [get] func (d *DstMapHandler) GetPlayerSessionFile(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) clusterPath := d.archiveResolver.ClusterPath(clusterName) levelName := ctx.Query("levelName") kuId := ctx.Query("kuId") if levelName == "" || kuId == "" { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "levelName or kuId 参数不能为空", }) return } baseSessionFile := filepath.Join(clusterPath, levelName, "save", "session") latestMetaFile, err2 := findLatestMetaFile(baseSessionFile) if err2 != nil { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: err2.Error(), }) return } sessionID := extractSessionID(latestMetaFile) sessionPath := filepath.Join(baseSessionFile, sessionID, kuId+"_") log.Println(sessionPath) filePath, err := findLatestPlayerFile(sessionPath) if err != nil { log.Panicln(err) } log.Println(filePath) file, err := fileUtils.ReadFile(filePath) if err != nil { log.Panicln(err) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: file, }) } func findLatestPlayerFile(directory string) (string, error) { // 检查指定目录是否存在 _, err := os.Stat(directory) if os.IsNotExist(err) { return "", fmt.Errorf("目录不存在:%s", directory) } // 用于存储最新的.meta文件路径和其修改时间 var latestFile string var latestFileTime time.Time // 获取指定目录下所有的文件 files, err := ioutil.ReadDir(directory) if err != nil { return "", fmt.Errorf("读取目录失败:%s", err) } for _, file := range files { // 检查文件是否是文件 if !file.IsDir() { // 获取文件的修改时间 modifiedTime := file.ModTime() // 如果找到的文件的修改时间比当前最新的.meta文件的修改时间更晚,则更新最新的.meta文件路径和修改时间 if modifiedTime.After(latestFileTime) { latestFile = filepath.Join(directory, file.Name()) latestFileTime = modifiedTime } } } if latestFile == "" { return "", fmt.Errorf("未找到文件") } return latestFile, nil } func extractSessionPrefix(sessionFile string) string { parts := strings.Split(sessionFile, "/") if len(parts) >= 2 { return parts[0] + "/" + parts[1] } return sessionFile } const sessionPrefix = "/save/session/" // extractSessionID 提取 /save/session/ 后的第一个路径段(如 925F2AFB73839B9E) func extractSessionID(p string) string { // 找到 "/save/session/" 的起始位置 i := strings.Index(p, sessionPrefix) // 由于题目保证一定存在,可直接跳过错误检查 rest := p[i+len(sessionPrefix):] // 取第一个 '/' 之前的部分(即 session ID) if j := strings.Index(rest, "/"); j != -1 { return rest[:j] } // 理论上不会走到这里(因为后面还有子目录如 /0000000002),但为安全起见: return rest // 整个剩余部分(如路径恰好以 ID 结尾) } func findLatestMetaFile(directory string) (string, error) { // 检查指定目录是否存在 _, err := os.Stat(directory) if os.IsNotExist(err) { return "", fmt.Errorf("目录不存在:%s", directory) } // 获取指定目录下一级的所有子目录 subdirs, err := ioutil.ReadDir(directory) if err != nil { return "", fmt.Errorf("读取目录失败:%s", err) } // 用于存储最新的.meta文件路径和其修改时间 var latestMetaFile string var latestMetaFileTime time.Time for _, subdir := range subdirs { // 检查子目录是否是目录 if subdir.IsDir() { subdirPath := filepath.Join(directory, subdir.Name()) // 获取子目录下的所有文件 files, err := ioutil.ReadDir(subdirPath) if err != nil { return "", fmt.Errorf("读取子目录失败:%s", err) } for _, file := range files { // 检查文件是否是.meta文件 if !file.IsDir() && filepath.Ext(file.Name()) != ".meta" { // 获取文件的修改时间 modifiedTime := file.ModTime() // 如果找到的文件的修改时间比当前最新的.meta文件的修改时间更晚,则更新最新的.meta文件路径和修改时间 if modifiedTime.After(latestMetaFileTime) { latestMetaFile = filepath.Join(subdirPath, file.Name()) latestMetaFileTime = modifiedTime } } } } } if latestMetaFile == "" { return "", fmt.Errorf("未找到文件") } return latestMetaFile, nil } ================================================ FILE: internal/api/handler/game_config_handler.go ================================================ package handler import ( "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/gameConfig" "log" "net/http" "github.com/gin-gonic/gin" ) type GameConfigHandler struct { gameConfig *gameConfig.GameConfig } func NewGameConfigHandler(gameConfig *gameConfig.GameConfig) *GameConfigHandler { return &GameConfigHandler{ gameConfig: gameConfig, } } func (p *GameConfigHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/game/8level/clusterIni", p.GetClusterIni) router.POST("/api/game/8level/clusterIni", p.SaveClusterIni) router.GET("/api/game/8level/adminilist", p.GetAdminList) router.POST("/api/game/8level/adminilist", p.SaveAdminList) router.GET("/api/game/8level/blacklist", p.GetBlackList) router.POST("/api/game/8level/blacklist", p.SaveBlackList) router.GET("/api/game/8level/whitelist", p.GetWhithList) router.POST("/api/game/8level/whitelist", p.SaveWhithList) router.GET("/api/game/config", p.GetConfig) router.POST("/api/game/config", p.SaveConfig) } // GetClusterIni 获取房间 cluster.ini 配置 swagger 注释 // @Summary 获取房间 cluster.ini 配置 // @Description 获取房间 cluster.ini 配置 // @Tags gameConfig // @Accept json // @Produce json // @Success 200 {object} response.Response{data=gameConfig.ClusterIniConfig} // @Router /api/game/config/clusterIni [get] func (p *GameConfigHandler) GetClusterIni(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) config, err := p.gameConfig.GetClusterIniConfig(clusterName) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: config, }) } // SaveClusterIni 保存房间 cluster.ini 配置 swagger 注释 // @Summary 保存房间 cluster.ini 配置 // @Description 保存房间 cluster.ini 配置 // @Tags gameConfig // @Accept json // @Produce json // @Param config body gameConfig.ClusterIniConfig true "cluster.ini 配置" // @Success 200 {object} response.Response // @Router /api/game/config/clusterIni [post] func (p *GameConfigHandler) SaveClusterIni(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var config gameConfig.ClusterIniConfig if err := ctx.ShouldBindJSON(&config); err != nil { ctx.JSON(400, response.Response{ Code: http.StatusBadRequest, Msg: "Invalid request body", Data: nil, }) return } err := p.gameConfig.SaveClusterIniConfig(clusterName, &config) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: nil, }) } // GetAdminList 获取房间 adminlist.txt 配置 swagger 注释 // @Summary 获取房间 adminlist.txt 配置 // @Description 获取房间 adminlist.txt 配置 // @Tags gameConfig // @Accept json // @Produce json // @Success 200 {object} response.Response{data=[]string} // @Router /api/game/config/adminlist [get] func (p *GameConfigHandler) GetAdminList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) list, err := p.gameConfig.GetAdminList(clusterName) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: list, }) } // SaveAdminList 保存房间 adminlist.txt 配置 swagger 注释 // @Summary 保存房间 adminlist.txt 配置 // @Description 保存房间 adminlist.txt 配置 // @Tags gameConfig // @Accept json // @Produce json // @Param list body []string true "adminlist.txt 配置" // @Success 200 {object} response.Response // @Router /api/game/config/adminlist [post] func (p *GameConfigHandler) SaveAdminList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var payload struct { List []string `json:"adminlist"` } if err := ctx.ShouldBindJSON(&payload); err != nil { ctx.JSON(400, response.Response{ Code: http.StatusBadRequest, Msg: "Invalid request body", Data: nil, }) return } err := p.gameConfig.SaveAdminList(clusterName, payload.List) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: nil, }) } // GetBlackList 获取房间 blacklist.txt 配置 swagger 注释 // @Summary 获取房间 blacklist.txt 配置 // @Description 获取房间 blacklist.txt 配置 // @Tags gameConfig // @Accept json // @Produce json // @Success 200 {object} response.Response{data=[]string} // @Router /api/game/config/blacklist [get] func (p *GameConfigHandler) GetBlackList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) list, err := p.gameConfig.GetBlackList(clusterName) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: list, }) } // SaveBlackList 保存房间 blacklist.txt 配置 swagger 注释 // @Summary 保存房间 blacklist.txt 配置 // @Description 保存房间 blacklist.txt 配置 // @Tags gameConfig // @Accept json // @Produce json // @Param list body []string true "blacklist.txt 配置" // @Success 200 {object} response.Response // @Router /api/game/config/blacklist [post] func (p *GameConfigHandler) SaveBlackList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var payload struct { List []string `json:"blacklist"` } if err := ctx.ShouldBindJSON(&payload); err != nil { ctx.JSON(400, response.Response{ Code: http.StatusBadRequest, Msg: "Invalid request body", Data: nil, }) return } err := p.gameConfig.SaveBlackList(clusterName, payload.List) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: nil, }) } // GetWhithList 获取房间 whitelist.txt 配置 swagger 注释 // @Summary 获取房间 whitelist.txt 配置 // @Description 获取房间 whitelist.txt 配置 // @Tags gameConfig // @Accept json // @Produce json // @Success 200 {object} response.Response{data=[]string} // @Router /api/game/config/whitelist [get] func (p *GameConfigHandler) GetWhithList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) list, err := p.gameConfig.GetWhithList(clusterName) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: list, }) } // SaveWhithList 保存房间 whitelist.txt 配置 swagger 注释 // @Summary 保存房间 whitelist.txt 配置 // @Description 保存房间 whitelist.txt 配置 // @Tags gameConfig // @Accept json // @Produce json // @Param list body []string true "whitelist.txt 配置" // @Success 200 {object} response.Response // @Router /api/game/config/whitelist [post] func (p *GameConfigHandler) SaveWhithList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var payload struct { List []string `json:"whitelist"` } if err := ctx.ShouldBindJSON(&payload); err != nil { ctx.JSON(400, response.Response{ Code: http.StatusBadRequest, Msg: "Invalid request body", Data: nil, }) return } err := p.gameConfig.SaveWhithList(clusterName, payload.List) if err != nil { ctx.JSON(500, response.Response{ Code: http.StatusInternalServerError, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: http.StatusOK, Msg: "success", Data: nil, }) } // GetConfig 获取房间配置 swagger 注释 // @Summary 获取房间配置 // @Description 获取房间配置 // @Tags gameConfig // @Accept json // @Produce json // @Success 200 {object} response.Response{data=gameConfig.HomeConfigVO} // @Router /api/game/config [get] func (p *GameConfigHandler) GetConfig(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) config, err := p.gameConfig.GetHomeConfig(clusterName) if err != nil { ctx.JSON(200, response.Response{ Code: 500, Msg: err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: 200, Msg: "success", Data: config, }) } func (p *GameConfigHandler) SaveConfig(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) config := gameConfig.HomeConfigVO{} err := ctx.ShouldBind(&config) if err != nil { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "Invalid request body", }) return } log.Println(config) p.gameConfig.SaveConfig(clusterName, config) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "save dst server config success", }) } ================================================ FILE: internal/api/handler/game_handler.go ================================================ package handler import ( "dst-admin-go/internal/middleware" "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/pkg/utils/shellUtils" "dst-admin-go/internal/pkg/utils/systemUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/game" "dst-admin-go/internal/service/gameArchive" "dst-admin-go/internal/service/level" "dst-admin-go/internal/service/levelConfig" "encoding/json" "log" "net/http" "runtime" "strings" "sync" "time" "github.com/gin-gonic/gin" ) type GameHandler struct { process game.Process level *level.LevelService gameArchive *gameArchive.GameArchive levelConfigUtils *levelConfig.LevelConfigUtils archive *archive.PathResolver } func NewGameHandler(process game.Process, levelService *level.LevelService, gameArchive *gameArchive.GameArchive, levelConfigUtils *levelConfig.LevelConfigUtils, archive *archive.PathResolver) *GameHandler { return &GameHandler{ process: process, level: levelService, gameArchive: gameArchive, levelConfigUtils: levelConfigUtils, archive: archive, } } func (p *GameHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/game/8level/start", p.Start, middleware.StartBeforeMiddleware(p.archive, p.levelConfigUtils)) router.GET("/api/game/8level/stop", p.Stop) router.GET("/api/game/8level/start/all", p.StartAll, middleware.StartBeforeMiddleware(p.archive, p.levelConfigUtils)) router.GET("/api/game/8level/stop/all", p.StopAll) router.POST("/api/game/8level/command", p.Command) router.GET("/api/game/8level/status", p.Status) router.GET("/api/game/archive", p.GameArchive) router.GET("/api/game/system/info/stream", p.SystemInfoStream) } // Stop 停止世界 swagger 注释 // @Summary 停止世界 // @Description 停止世界 // @Tags game // @Accept json // @Produce json // @Param levelName query string true "世界名称" // @Success 200 {object} response.Response // @Router /api/game/stop [get] func (p *GameHandler) Stop(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) levelName := ctx.Query("levelName") if levelName == "" { ctx.JSON(400, response.Response{Code: 400, Msg: "levelName query parameter is required"}) return } err := p.process.Stop(clusterName, levelName) if err != nil { ctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: "failed to stop game server: " + err.Error()}) } else { ctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: "success"}) } } // Start 启动世界 swagger 注释 // @Summary 启动世界 // @Description 启动世界 // @Tags game // @Accept json // @Produce json // @Param levelName query string true "世界名称" // @Success 200 {object} response.Response // @Router /api/game/start [get] func (p *GameHandler) Start(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) levelName := ctx.Query("levelName") if levelName == "" { ctx.JSON(400, response.Response{Code: 400, Msg: "levelName query parameter is required"}) return } err := p.process.Start(clusterName, levelName) if err != nil { ctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: "failed to start game server: " + err.Error()}) } else { ctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: "success"}) } } // StartAll 启动所有世界 swagger 注释 // @Summary 启动所有世界 // @Description 启动所有世界 // @Tags game // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/game/start/all [get] func (p *GameHandler) StartAll(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) err := p.process.StartAll(clusterName) if err != nil { ctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: "failed to start all game servers: " + err.Error()}) } else { ctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: "success"}) } } // StopAll 停止所有世界 swagger 注释 // @Summary 停止所有世界 // @Description 停止所有世界 // @Tags game // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/game/stop/all [get] func (p *GameHandler) StopAll(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) err := p.process.StopAll(clusterName) if err != nil { ctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: "failed to stop all game servers: " + err.Error()}) } else { ctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: "success"}) } } // Command 运行命令 swagger 注释 // @Summary 运行命令 // @Description 运行命令 // @Tags game // @Accept json // @Produce json // @Param command query string true "命令" // @Success 200 {object} response.Response // @Router /api/game/command [post] func (p *GameHandler) Command(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) type payload struct { Command string `json:"command"` LevelName string `json:"levelName"` } var command payload if err := ctx.ShouldBindJSON(&command); err != nil { ctx.JSON(400, response.Response{Code: 400, Msg: "Invalid request body"}) return } if command.LevelName == "" { ctx.JSON(400, response.Response{Code: 400, Msg: "levelName query parameter is required"}) return } status, err := p.process.Status(clusterName, command.LevelName) if !status { ctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: "game server is not running"}) return } err = p.process.Command(clusterName, command.LevelName, command.Command) if err != nil { ctx.JSON(http.StatusOK, response.Response{Code: 500, Msg: "failed to run command: " + err.Error()}) return } ctx.JSON(http.StatusOK, response.Response{Code: 200, Msg: "success"}) } type LevelStatus struct { Ps game.DstPsAux `json:"Ps"` RunVersion int64 `json:"runVersion"` Status bool `json:"status"` IsMaster bool `json:"isMaster"` LevelName string `json:"levelName"` Uuid string `json:"uuid"` Leveldataoverride string `json:"leveldataoverride"` Modoverrides string `json:"modoverrides"` ServerIni levelConfig.ServerIni `json:"serverIni"` } // Status 获取服务器状态 // @Summary 获取服务器状态 // @Description 获取所有世界的运行状态信息 // @Tags game // @Accept json // @Produce json // @Success 200 {object} response.Response{data=[]LevelStatus} // @Router /api/game/8level/status [get] func (p *GameHandler) Status(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) levelList := p.level.GetLevelList(clusterName) length := len(levelList) result := make([]LevelStatus, length) if runtime.GOOS == "windows" { var wg sync.WaitGroup wg.Add(length) for i := range levelList { go func(index int) { defer func() { wg.Done() if r := recover(); r != nil { } }() levelItem := levelList[index] ps := p.process.PsAuxSpecified(clusterName, levelItem.Uuid) status, _ := p.process.Status(clusterName, levelItem.Uuid) result[index] = LevelStatus{ Ps: ps, Status: status, RunVersion: levelItem.RunVersion, LevelName: levelItem.LevelName, IsMaster: levelItem.IsMaster, Uuid: levelItem.Uuid, Leveldataoverride: levelItem.Leveldataoverride, Modoverrides: levelItem.Modoverrides, ServerIni: levelItem.ServerIni, } }(i) } wg.Wait() ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: result, }) } else { for i := range levelList { levelItem := levelList[i] result[i] = LevelStatus{ Status: false, RunVersion: levelItem.RunVersion, LevelName: levelItem.LevelName, IsMaster: levelItem.IsMaster, Uuid: levelItem.Uuid, Leveldataoverride: levelItem.Leveldataoverride, Modoverrides: levelItem.Modoverrides, ServerIni: levelItem.ServerIni, } } cmd := "ps -aux | grep -v grep | grep -v tail | grep -v SCREEN | grep " + clusterName + " |awk '{print $3, $4, $5, $6,$16}'" info, err := shellUtils.Shell(cmd) if err != nil { log.Println(cmd + " error: " + err.Error()) } else { lines := strings.Split(info, "\n") for lineIndex := range lines { dstPsVo := game.DstPsAux{} arr := strings.Split(lines[lineIndex], " ") if len(arr) > 4 { dstPsVo.CpuUage = strings.Replace(arr[0], "\n", "", -1) dstPsVo.MemUage = strings.Replace(arr[1], "\n", "", -1) dstPsVo.VSZ = strings.Replace(arr[2], "\n", "", -1) dstPsVo.RSS = strings.Replace(arr[3], "\n", "", -1) for i := range result { levelName := result[i].Uuid if strings.Contains(arr[4], levelName) { result[i].Ps = dstPsVo result[i].Status = true } } } } } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: result, }) } } // GameArchive 获取游戏存档列表 // @Summary 获取游戏存档列表 // @Description 获取当前集群的游戏存档列表 // @Tags game // @Accept json // @Produce json // @Success 200 {object} response.Response{gameArchive.GameArchiveInfo} // @Router /api/game/archive [get] func (p *GameHandler) GameArchive(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) archiveInfo := p.gameArchive.GetGameArchive(clusterName) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: archiveInfo, }) } // SystemInfoStream 系统信息流 // @Summary 系统信息流 // @Description 获取服务器系统信息的实时流 (SSE) // @Tags game // @Accept text/event-stream // @Produce text/event-stream // @Success 200 {string} string "SSE 格式的系统信息流" // @Router /api/game/system/info/stream [get] func (p *GameHandler) SystemInfoStream(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) // 设置SSE响应头 ctx.Header("Content-Type", "text/event-stream") ctx.Header("Cache-Control", "no-cache") ctx.Header("Connection", "keep-alive") ctx.Header("X-Accel-Buffering", "no") // 创建一个ticker,每2秒推送一次数据 ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() // 使用context来检测客户端断开连接 clientGone := ctx.Request.Context().Done() // 立即发送第一次数据 p.sendSystemInfoData(ctx, clusterName) for { select { case <-clientGone: log.Println("Client disconnected from system info stream") return case <-ticker.C: p.sendSystemInfoData(ctx, clusterName) } } } func (p *GameHandler) sendSystemInfoData(ctx *gin.Context, clusterName string) { systemInfo := p.GetSystemInfo(clusterName) // 构造响应数据 response := response.Response{ Code: 200, Msg: "success", Data: systemInfo, } // 将数据序列化为JSON data, err := json.Marshal(response) if err != nil { log.Println("Failed to marshal system info data:", err) return } // 发送SSE数据 ctx.SSEvent("message", string(data)) ctx.Writer.Flush() } type SystemInfo struct { HostInfo *systemUtils.HostInfo `json:"host"` CpuInfo *systemUtils.CpuInfo `json:"cpu"` MemInfo *systemUtils.MemInfo `json:"mem"` DiskInfo *systemUtils.DiskInfo `json:"disk"` PanelMemUsage uint64 `json:"panelMemUsage"` PanelCpuUsage float64 `json:"panelCpuUsage"` } func (p *GameHandler) GetSystemInfo(clusterName string) *SystemInfo { var wg sync.WaitGroup wg.Add(5) dashboardVO := SystemInfo{} go func() { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() dashboardVO.HostInfo = systemUtils.GetHostInfo() }() go func() { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() dashboardVO.CpuInfo = systemUtils.GetCpuInfo() }() go func() { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() dashboardVO.MemInfo = systemUtils.GetMemInfo() }() go func() { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() dashboardVO.DiskInfo = systemUtils.GetDiskInfo() }() go func() { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() var m runtime.MemStats runtime.ReadMemStats(&m) dashboardVO.PanelMemUsage = m.Alloc / 1024 // 将字节转换为MB }() wg.Wait() return &dashboardVO } ================================================ FILE: internal/api/handler/kv_handler.go ================================================ package handler import ( "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/response" "log" "net/http" "github.com/gin-gonic/gin" "gorm.io/gorm" ) type KvHandler struct { db *gorm.DB } func NewKvHandler(db *gorm.DB) *KvHandler { return &KvHandler{ db: db, } } func (i *KvHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/kv", i.GetKv) router.POST("/api/kv", i.SaveKv) } // GetKv 生成 swagger 文档注释 // @Summary 获取kv值 // @Description 获取kv值 // @Tags kv // @Param key query string true "key" // @Success 200 {object} response.Response // @Router /api/kv [get] func (i *KvHandler) GetKv(ctx *gin.Context) { key := ctx.Query("key") db := i.db kv := model.KV{} db.Where("key = ?", key).Find(&kv) //if kv.Value != "Y" { ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: kv.Value, }) } // SaveKv 生成 swagger 文档注释 // @Summary 保存kv值 // @Description 保存kv值 // @Tags kv // @Param key formData string true "key" // @Param value formData string true "value" // @Success 200 {object} response.Response // @Router /api/kv [post] func (i *KvHandler) SaveKv(ctx *gin.Context) { kv := model.KV{} err := ctx.ShouldBind(&kv) if err != nil { log.Panicln(err) } db := i.db oldKv := model.KV{} db.Where("key = ?", kv.Key).Find(&oldKv) if oldKv.ID == 0 { db.Create(&kv) } else { oldKv.Value = kv.Value db.Save(&oldKv) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: kv.Value, }) } ================================================ FILE: internal/api/handler/level_handler.go ================================================ package handler import ( "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/level" "dst-admin-go/internal/service/levelConfig" "net/http" "github.com/gin-gonic/gin" ) type LevelHandler struct { levelService *level.LevelService } func NewLevelHandler(levelService *level.LevelService) *LevelHandler { return &LevelHandler{ levelService: levelService, } } func (h *LevelHandler) RegisterRoute(router *gin.RouterGroup) { level := router.Group("/api/cluster/level") { level.GET("", h.GetLevelList) level.POST("", h.CreateLevel) level.DELETE("", h.DeleteLevel) level.PUT("", h.UpdateLevels) } } // GetLevelList 获取世界列表 // @Summary 获取世界列表 // @Description 获取当前集群的所有世界(等级)列表 // @Tags level // @Accept json // @Produce json // @Success 200 {object} response.Response{data=[]levelConfig.LevelInfo} // @Router /api/cluster/level [get] func (h *LevelHandler) GetLevelList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) levels := h.levelService.GetLevelList(clusterName) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "get level list success", Data: levels, }) } // UpdateLevel 更新世界 // @Summary 更新世界 // @Description 更新指定世界的配置信息 // @Tags level // @Accept json // @Produce json // @Param level body levelConfig.LevelInfo true "世界配置信息" // @Success 200 {object} response.Response // @Router /api/cluster/level [put] func (h *LevelHandler) UpdateLevel(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var world levelConfig.LevelInfo if err := ctx.BindJSON(&world); err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 400, Msg: "invalid request", Data: nil, }) return } err := h.levelService.UpdateLevel(clusterName, &world) if err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 500, Msg: "update level failed", Data: nil, }) return } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "update level success", Data: nil, }) } // CreateLevel 创建世界 // @Summary 创建世界 // @Description 创建一个新的世界(等级) // @Tags level // @Accept json // @Produce json // @Param level body levelConfig.LevelInfo true "世界配置信息" // @Success 200 {object} response.Response // @Router /api/cluster/level [post] func (h *LevelHandler) CreateLevel(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var world levelConfig.LevelInfo if err := ctx.BindJSON(&world); err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 400, Msg: "invalid request", Data: nil, }) return } err := h.levelService.CreateLevel(clusterName, &world) if err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 500, Msg: "create level failed", Data: nil, }) return } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "create level success", Data: world, }) } // DeleteLevel 删除世界 // @Summary 删除世界 // @Description 删除指定的世界 // @Tags level // @Accept json // @Produce json // @Param levelName query string true "世界名称" // @Success 200 {object} response.Response // @Router /api/cluster/level [delete] func (h *LevelHandler) DeleteLevel(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) levelName := ctx.Query("levelName") err := h.levelService.DeleteLevel(clusterName, levelName) if err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 500, Msg: "delete level failed", Data: nil, }) return } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "delete level success", Data: nil, }) } // UpdateLevels 批量更新世界 // @Summary 批量更新世界 // @Description 批量更新多个世界的配置信息 // @Tags level // @Accept json // @Produce json // @Param levels body []levelConfig.LevelInfo true "世界配置信息列表" // @Success 200 {object} response.Response // @Router /api/cluster/level [put] func (h *LevelHandler) UpdateLevels(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) var payload struct { Levels []levelConfig.LevelInfo `json:"levels"` } if err := ctx.BindJSON(&payload); err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 400, Msg: "invalid request", Data: nil, }) return } err := h.levelService.UpdateLevels(clusterName, payload.Levels) if err != nil { ctx.JSON(http.StatusOK, response.Response{ Code: 500, Msg: "update levels failed", Data: nil, }) return } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "update levels success", Data: nil, }) } ================================================ FILE: internal/api/handler/level_log_handler.go ================================================ package handler import ( "bufio" "bytes" "context" clusterContext "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/archive" "fmt" "io" "net/http" "os" "strconv" "strings" "time" "github.com/gin-gonic/gin" ) type LevelLogHandler struct { archive *archive.PathResolver } func NewLevelLogHandler(archive *archive.PathResolver) *LevelLogHandler { return &LevelLogHandler{ archive: archive, } } func (h *LevelLogHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/game/log/stream", h.Stream) router.GET("/api/game/level/server/log", h.GetServerLog) router.GET("/api/game/level/server/download", h.DownloadServerLog) } // Stream 服务器日志流 // @Summary 服务器日志流 // @Description 获取指定世界的实时日志流 (SSE) // @Tags log // @Accept text/event-stream // @Produce text/event-stream // @Param clusterName query string false "集群名称" // @Param levelName query string true "世界名称" // @Success 200 {string} string "SSE 格式的日志流" // @Router /api/game/log/stream [get] func (h *LevelLogHandler) Stream(c *gin.Context) { clusterName := clusterContext.GetClusterName(c) levelName := c.Query("levelName") if clusterName == "" || levelName == "" { c.JSON(400, gin.H{"error": "cluster and level required"}) return } w := c.Writer flusher, ok := w.(http.Flusher) if !ok { c.JSON(500, gin.H{"error": "streaming unsupported"}) return } // SSE headers w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") w.Header().Set("X-Accel-Buffering", "no") // nginx ctx := c.Request.Context() // 1️⃣ snapshot serverLogPath := h.archive.ServerLogPath(clusterName, levelName) lines, err := reader.Snapshot(serverLogPath, 100) if err != nil { c.JSON(500, gin.H{"error": err.Error()}) return } for _, line := range lines { writeSSE(w, "log", line) } flusher.Flush() // 2️⃣ follow ch, cancel, err := reader.Follow(serverLogPath) if err != nil { writeSSE(w, "error", err.Error()) flusher.Flush() return } defer cancel() heartbeat := time.NewTicker(15 * time.Second) defer heartbeat.Stop() for { select { case <-ctx.Done(): return case line, ok := <-ch: if !ok { return } writeSSE(w, "log", line) flusher.Flush() case <-heartbeat.C: writeSSE(w, "ping", "") flusher.Flush() } } } // GetServerLog 获取服务器日志 swagger 注释 // @Summary 获取服务器日志 // @Description 获取指定世界的服务器日志(默认最近100行) // @Tags log // @Produce application/json // @Param clusterName query string false "集群名称" // @Param levelName query string true "世界名称" // @Param lines query string false "返回日志行数,默认为100" // @Success 200 {object} response.Response{data=[]string} "服务器日志列表" // @Router /api/game/level/server/log [get] func (h *LevelLogHandler) GetServerLog(ctx *gin.Context) { clusterName := clusterContext.GetClusterName(ctx) levelName := ctx.Query("levelName") lines := ctx.DefaultQuery("lines", "100") if clusterName == "" || levelName == "" { ctx.JSON(400, gin.H{"error": "cluster and level required"}) return } serverLogPath := h.archive.ServerLogPath(clusterName, levelName) linesInt, err := strconv.Atoi(lines) if err != nil { ctx.JSON(400, gin.H{"error": "lines must be a number"}) return } read, err := fileUtils.ReverseRead(serverLogPath, uint(linesInt)) if err != nil { ctx.JSON(200, response.Response{ Code: 500, Msg: "failed to read server log: " + err.Error(), Data: nil, }) return } ctx.JSON(200, response.Response{ Code: 200, Data: read, Msg: "success", }) } // DownloadServerLog 下载服务器日志 swagger 注释 // @Summary 下载服务器日志 // @Description 下载指定世界的完整服务器日志文件 // @Tags log // @Produce application/octet-stream // @Param clusterName query string false "集群名称" // @Param levelName query string true "世界名称" // @Success 200 {file} file "服务器日志文件" // @Router /api/game/level/server/download [get] func (h *LevelLogHandler) DownloadServerLog(ctx *gin.Context) { clusterName := clusterContext.GetClusterName(ctx) levelName := ctx.Query("levelName") if clusterName == "" || levelName == "" { ctx.JSON(400, gin.H{"error": "cluster and level required"}) return } serverLogPath := h.archive.ServerLogPath(clusterName, levelName) ctx.Header("Content-Type", "application/octet-stream") ctx.Header("Content-Disposition", "attachment; filename="+"server_log.txt") ctx.Header("Content-Transfer-Encoding", "binary") ctx.File(serverLogPath) } func writeSSE(w io.Writer, event, data string) { if event != "" { fmt.Fprintf(w, "event: %s\n", event) } // data 可能包含换行,必须逐行写 scanner := bufio.NewScanner(strings.NewReader(data)) for scanner.Scan() { fmt.Fprintf(w, "data: %s\n", scanner.Text()) } fmt.Fprint(w, "\n") } var reader = NewFileLogReader() type FileLogReader struct { interval time.Duration } func NewFileLogReader() *FileLogReader { return &FileLogReader{ interval: time.Second, } } func (r *FileLogReader) Snapshot( serverLogPath string, n int, ) ([]string, error) { path := serverLogPath f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() stat, err := f.Stat() if err != nil { return nil, err } var ( size = stat.Size() offset = size lines []string buf []byte ) for offset > 0 && len(lines) < n { readSize := int64(4096) if offset < readSize { readSize = offset } offset -= readSize chunk := make([]byte, readSize) _, err := f.ReadAt(chunk, offset) if err != nil && err != io.EOF { return nil, err } buf = append(chunk, buf...) for { idx := bytes.LastIndexByte(buf, '\n') if idx < 0 { break } line := strings.TrimRight(string(buf[idx+1:]), "\r") lines = append(lines, line) buf = buf[:idx] if len(lines) >= n { break } } } // 反转 for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 { lines[i], lines[j] = lines[j], lines[i] } return lines, nil } func (r *FileLogReader) Follow( serverLogPath string, ) (<-chan string, func(), error) { path := serverLogPath f, err := os.Open(path) if err != nil { return nil, nil, err } stat, err := f.Stat() if err != nil { f.Close() return nil, nil, err } out := make(chan string, 100) ctx, cancel := context.WithCancel(context.Background()) offset := stat.Size() go func() { defer close(out) defer f.Close() reader := bufio.NewReader(f) for { select { case <-ctx.Done(): return case <-time.After(r.interval): stat, err := f.Stat() if err != nil { continue } // 文件被 truncate if stat.Size() < offset { offset = 0 f.Seek(0, io.SeekStart) reader.Reset(f) } if stat.Size() == offset { continue } f.Seek(offset, io.SeekStart) reader.Reset(f) for { line, err := reader.ReadString('\n') if err != nil { break } offset += int64(len(line)) out <- strings.TrimRight(line, "\r\n") } } } }() return out, cancel, nil } ================================================ FILE: internal/api/handler/login_handler.go ================================================ package handler import ( "dst-admin-go/internal/database" "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/login" "log" "net/http" "github.com/gin-gonic/gin" "gorm.io/gorm" ) const ( PasswordPath = "./password.txt" ) type LoginHandler struct { loginService *login.LoginService } func NewLoginHandler(loginService *login.LoginService) *LoginHandler { return &LoginHandler{ loginService: loginService, } } func (h *LoginHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/user", h.GetUserInfo) router.POST("/api/login", h.Login) router.GET("/api/logout", h.Logout) router.POST("/api/change/password", h.ChangePassword) router.POST("/api/user", h.UpdateUserInfo) router.GET("/api/init", h.CheckIsFirst) router.POST("/api/init", h.InitFirst) } // GetUserInfo 获取用户信息 // @Summary 获取用户信息 // @Description 获取用户信息 // @Tags user // @Accept json // @Produce json // @Success 200 {object} response.Response{data=login.UserInfo} // @Router /api/user/info [get] func (h *LoginHandler) GetUserInfo(ctx *gin.Context) { ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "Init user success", Data: h.loginService.GetUserInfo(), }) } // Login 用户登录 // @Summary 用户登录 // @Description 用户登录 // @Tags user // @Accept json // @Produce json // @Param user body login.UserInfo true "用户信息" // @Success 200 {object} response.Response // @Router /api/user/login [post] func (h *LoginHandler) Login(ctx *gin.Context) { var userInfo login.UserInfo err := ctx.ShouldBind(&userInfo) if err != nil { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "Invalid request body: " + err.Error(), Data: nil, }) return } response := h.loginService.Login(userInfo, ctx) ctx.JSON(http.StatusOK, response) } // Logout 用户登出 // @Summary 用户登出 // @Description 用户登出 // @Tags user // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/user/logout [get] func (h *LoginHandler) Logout(ctx *gin.Context) { h.loginService.Logout(ctx) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "Logout success", Data: nil, }) } // ChangePassword 修改密码 // @Summary 修改密码 // @Description 修改密码 // @Tags user // @Accept json // @Produce json // @Param password body object true "新密码" // @Success 200 {object} response.Response // @Router /api/user/changePassword [post] func (h *LoginHandler) ChangePassword(ctx *gin.Context) { var body struct { NewPassword string `json:"newPassword"` } if err := ctx.BindJSON(&body); err != nil { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "Invalid request body: " + err.Error(), Data: nil, }) return } response := h.loginService.ChangePassword(body.NewPassword) ctx.JSON(http.StatusOK, response) } // UpdateUserInfo 更新用户信息 // @Summary 更新用户信息 // @Description 更新用户信息 // @Tags user // @Accept json // @Produce json // @Param user body object true "用户信息" // @Success 200 {object} response.Response // @Router /api/user/update [post] func (h *LoginHandler) UpdateUserInfo(ctx *gin.Context) { var body struct { Username string `json:"username"` DisplayName string `json:"displayName"` PhotoURL string `json:"photoURL"` Password string `json:"password"` } if err := ctx.BindJSON(&body); err != nil { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "Invalid request body: " + err.Error(), Data: nil, }) return } err := fileUtils.WriterLnFile(PasswordPath, []string{ "username = " + body.Username, "password = " + body.Password, "displayName=" + body.DisplayName, "photoURL=" + body.PhotoURL, }) if err != nil { ctx.JSON(http.StatusInternalServerError, response.Response{ Code: 500, Msg: "修改用户信息失败: " + err.Error(), Data: nil, }) return } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "Update user info success", Data: nil, }) } // InitFirst 初始化首次用户 // @Summary 初始化首次用户 // @Description 初始化系统首次用户信息 // @Tags user // @Accept json // @Produce json // @Param userInfo body login.UserInfo true "用户信息" // @Success 200 {object} response.Response // @Router /api/init [post] func (h *LoginHandler) InitFirst(ctx *gin.Context) { db := database.Db kv := model.KV{} db.Where("key = 'FIRST_INIT'").First(&kv) if kv.Value == "TRUE" || fileUtils.Exists("./first") { log.Panicln("非法请求") } var payload struct { UserInfo login.UserInfo `json:"userInfo"` } err := ctx.BindJSON(&payload) if err != nil { ctx.JSON(http.StatusBadRequest, response.Response{ Code: 400, Msg: "Invalid request body: " + err.Error(), Data: nil, }) } // 事务 // 记录已经初始化 // 保存用户信息 err = db.Transaction(func(tx *gorm.DB) error { tx.Create(&model.KV{Key: "FIRST_INIT", Value: "TRUE"}) h.loginService.InitUserInfo(payload.UserInfo) return nil }) if err != nil { ctx.JSON(http.StatusInternalServerError, response.Response{ Code: 500, Msg: "初始化失败: " + err.Error(), Data: nil, }) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: nil, }) } // CheckIsFirst 检查是否首次初始化 // @Summary 检查是否首次初始化 // @Description 检查系统是否进行了首次初始化 // @Tags user // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/init [get] func (h *LoginHandler) CheckIsFirst(ctx *gin.Context) { exist := false db := database.Db kv := model.KV{} db.Where("key = 'FIRST_INIT'").First(&kv) if kv.Value == "TRUE" { exist = true } else { exist = fileUtils.Exists("./first") } code := 200 msg := "is first" if exist { code = 400 msg = "is not first" } ctx.JSON(http.StatusOK, response.Response{ Code: code, Msg: msg, Data: nil, }) } ================================================ FILE: internal/api/handler/mod_handler.go ================================================ package handler import ( "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/dstConfig" "dst-admin-go/internal/service/mod" "encoding/json" "log" "strconv" "github.com/gin-gonic/gin" ) type ModHandler struct { modService *mod.ModService dstConfig dstConfig.Config } func NewModHandler(modService *mod.ModService, dstConfig dstConfig.Config) *ModHandler { return &ModHandler{ modService: modService, dstConfig: dstConfig, } } func (h *ModHandler) RegisterRoute(router *gin.RouterGroup) { modGroup := router.Group("/api/mod") { modGroup.GET("/search", h.SearchModList) modGroup.GET("/:modId", h.GetModInfo) modGroup.PUT("/:modId", h.UpdateMod) modGroup.GET("", h.GetMyModList) modGroup.DELETE("/:modId", h.DeleteMod) modGroup.DELETE("/setup/workshop", h.DeleteSetupWorkshop) modGroup.GET("/modinfo/:modId", h.GetModInfoFile) modGroup.POST("/modinfo", h.SaveModInfoFile) modGroup.POST("/modinfo/file", h.AddModInfoFile) modGroup.PUT("/modinfo", h.UpdateAllModInfos) modGroup.GET("/ugc/acf", h.GetUgcModAcf) modGroup.DELETE("/ugc", h.DeleteUgcModFile) } } // SearchModList 搜索mod列表 // @Summary 搜索mod列表 // @Description 搜索Steam创意工坊中的模组 // @Tags mod // @Accept json // @Produce json // @Param text query string false "搜索关键词" // @Param page query int false "页码" default(1) // @Param size query int false "每页数量" default(10) // @Param lang query string false "语言" default(zh) // @Success 200 {object} response.Response{} // @Router /api/mod/search [get] func (h *ModHandler) SearchModList(ctx *gin.Context) { text := ctx.Query("text") page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1")) size, _ := strconv.Atoi(ctx.DefaultQuery("size", "10")) lang := ctx.DefaultQuery("lang", "zh") data, err := h.modService.SearchModList(text, page, size, lang) if err != nil { response.FailWithMessage("搜索mod失败: "+err.Error(), ctx) return } response.OkWithData(data, ctx) } // GetModInfo 获取mod信息 // @Summary 获取mod信息 // @Description 根据modId获取模组详细信息 // @Tags mod // @Accept json // @Produce json // @Param modId path string true "模组ID" // @Param lang query string false "语言" default(zh) // @Success 200 {object} response.Response // @Router /api/mod/{modId} [get] func (h *ModHandler) GetModInfo(ctx *gin.Context) { modId := ctx.Param("modId") lang := ctx.DefaultQuery("lang", "zh") clusterName := context.GetClusterName(ctx) modinfo, err := h.modService.SubscribeModByModId(clusterName, modId, lang) if err != nil { response.FailWithMessage("模组下载失败: "+err.Error(), ctx) return } var modConfig map[string]interface{} _ = json.Unmarshal([]byte(modinfo.ModConfig), &modConfig) modData := map[string]interface{}{ "auth": modinfo.Auth, "consumer_id": modinfo.ConsumerAppid, "creator_appid": modinfo.CreatorAppid, "description": modinfo.Description, "file_url": modinfo.FileUrl, "modid": modinfo.Modid, "img": modinfo.Img, "last_time": modinfo.LastTime, "name": modinfo.Name, "v": modinfo.V, "mod_config": modConfig, "update": modinfo.Update, } response.OkWithData(modData, ctx) } // GetMyModList 获取我的mod列表 // @Summary 获取我的mod列表 // @Description 获取已订阅的模组列表 // @Tags mod // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/mod [get] func (h *ModHandler) GetMyModList(ctx *gin.Context) { modInfos, err := h.modService.GetMyModList() if err != nil { response.FailWithMessage("获取模组列表失败: "+err.Error(), ctx) return } var modDataList []map[string]interface{} for _, modinfo := range modInfos { var modConfig map[string]interface{} _ = json.Unmarshal([]byte(modinfo.ModConfig), &modConfig) modData := map[string]interface{}{ "auth": modinfo.Auth, "consumer_id": modinfo.ConsumerAppid, "creator_appid": modinfo.CreatorAppid, "description": modinfo.Description, "file_url": modinfo.FileUrl, "modid": modinfo.Modid, "img": modinfo.Img, "last_time": modinfo.LastTime, "name": modinfo.Name, "v": modinfo.V, "mod_config": modConfig, "update": modinfo.Update, } modDataList = append(modDataList, modData) } response.OkWithData(modDataList, ctx) } // UpdateAllModInfos 批量更新模组信息 // @Summary 批量更新模组信息 // @Description 批量更新所有已订阅模组的信息 // @Tags mod // @Accept json // @Produce json // @Param lang query string false "语言" default(zh) // @Success 200 {object} response.Response // @Router /api/mod/modinfo [put] func (h *ModHandler) UpdateAllModInfos(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) lang := ctx.DefaultQuery("lang", "zh") err := h.modService.UpdateAllModInfos(clusterName, lang) if err != nil { response.FailWithMessage("更新失败: "+err.Error(), ctx) return } response.OkWithMessage("更新成功", ctx) } // DeleteMod 删除模组 // @Summary 删除模组 // @Description 根据modId删除模组 // @Tags mod // @Accept json // @Produce json // @Param modId path string true "模组ID" // @Success 200 {object} response.Response // @Router /api/mod/{modId} [delete] func (h *ModHandler) DeleteMod(ctx *gin.Context) { modId := ctx.Param("modId") clusterName := context.GetClusterName(ctx) err := h.modService.DeleteMod(clusterName, modId) if err != nil { response.FailWithMessage("删除失败: "+err.Error(), ctx) return } response.OkWithData(modId, ctx) } // DeleteSetupWorkshop 删除workshop文件 // @Summary 删除workshop文件 // @Description 删除所有workshop模组文件 // @Tags mod // @Accept json // @Produce json // @Success 200 {object} response.Response // @Router /api/mod/setup/workshop [delete] func (h *ModHandler) DeleteSetupWorkshop(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) err := h.modService.DeleteSetupWorkshop(clusterName) if err != nil { response.FailWithMessage("删除失败: "+err.Error(), ctx) return } response.OkWithMessage("删除成功", ctx) } // GetModInfoFile 获取模组配置文件 // @Summary 获取模组配置文件 // @Description 根据modId获取模组配置文件内容 // @Tags mod // @Accept json // @Produce json // @Param modId path string true "模组ID" // @Success 200 {object} response.Response{data=mod.ModInfo} // @Router /api/mod/modinfo/{modId} [get] func (h *ModHandler) GetModInfoFile(ctx *gin.Context) { modId := ctx.Param("modId") modInfo, err := h.modService.GetModByModId(modId) if err != nil { response.FailWithMessage("获取模组信息失败: "+err.Error(), ctx) return } response.OkWithData(modInfo, ctx) } // SaveModInfoFile 保存模组配置文件 // @Summary 保存模组配置文件 // @Description 保存模组配置信息 // @Tags mod // @Accept json // @Produce json // @Param data body mod.ModInfo true "模组信息" // @Success 200 {object} response.Response{data=mod.ModInfo} // @Router /api/mod/modinfo [post] func (h *ModHandler) SaveModInfoFile(ctx *gin.Context) { var modInfo model.ModInfo err := ctx.ShouldBindJSON(&modInfo) if err != nil { response.FailWithMessage("参数解析失败: "+err.Error(), ctx) return } err = h.modService.SaveModInfo(&modInfo) if err != nil { response.FailWithMessage("保存失败: "+err.Error(), ctx) return } response.OkWithData(modInfo, ctx) } // UpdateMod 更新模组 // @Summary 更新模组 // @Description 根据modId更新模组 // @Tags mod // @Accept json // @Produce json // @Param modId path string true "模组ID" // @Param lang query string false "语言" default(zh) // @Success 200 {object} response.Response // @Router /api/mod/{modId} [put] func (h *ModHandler) UpdateMod(ctx *gin.Context) { modId := ctx.Param("modId") clusterName := context.GetClusterName(ctx) lang := ctx.DefaultQuery("lang", "zh") // 删除旧数据 err := h.modService.DeleteMod(clusterName, modId) if err != nil { log.Println("删除旧模组失败:", err) } // 重新下载 modinfo, err := h.modService.SubscribeModByModId(clusterName, modId, lang) if err != nil { response.FailWithMessage("模组更新失败: "+err.Error(), ctx) return } var modConfig map[string]interface{} _ = json.Unmarshal([]byte(modinfo.ModConfig), &modConfig) modData := map[string]interface{}{ "auth": modinfo.Auth, "consumer_id": modinfo.ConsumerAppid, "creator_appid": modinfo.CreatorAppid, "description": modinfo.Description, "file_url": modinfo.FileUrl, "modid": modinfo.Modid, "img": modinfo.Img, "last_time": modinfo.LastTime, "name": modinfo.Name, "v": modinfo.V, "mod_config": modConfig, "update": modinfo.Update, } response.OkWithData(modData, ctx) } // AddModInfoFile 手动添加模组 // @Summary 手动添加模组 // @Description 手动添加模组配置文件 // @Tags mod // @Accept json // @Produce json // @Param data body object true "模组信息" example({"workshopId":"123456","modinfo":"模组配置内容"}) // @Param lang query string false "语言" default(zh) // @Success 200 {object} response.Response // @Router /api/mod/modinfo/file [post] func (h *ModHandler) AddModInfoFile(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) lang := ctx.DefaultQuery("lang", "zh") var payload struct { WorkshopId string `json:"workshopId"` Modinfo string `json:"modinfo"` } err := ctx.ShouldBindJSON(&payload) if err != nil { response.FailWithMessage("参数解析失败: "+err.Error(), ctx) return } if payload.WorkshopId == "" { response.FailWithMessage("workshopId不能为空", ctx) return } // 获取配置 config, err := h.dstConfig.GetDstConfig(clusterName) if err != nil { response.FailWithMessage("获取配置失败: "+err.Error(), ctx) return } err = h.modService.AddModInfo(clusterName, lang, payload.WorkshopId, payload.Modinfo, config.Mod_download_path) if err != nil { response.FailWithMessage("添加模组失败: "+err.Error(), ctx) return } response.OkWithMessage("添加成功", ctx) } // GetUgcModAcf 获取UGC mod acf文件信息 // @Summary 获取UGC mod acf文件信息 // @Description 获取UGC模组的ACF文件信息 // @Tags mod // @Accept json // @Produce json // @Param levelName query string true "世界名称" // @Success 200 {object} response.Response // @Router /api/mod/ugc/acf [get] func (h *ModHandler) GetUgcModAcf(ctx *gin.Context) { levelName := ctx.Query("levelName") clusterName := context.GetClusterName(ctx) workshopItemDetails, err := h.modService.GetUgcModInfo(clusterName, levelName) if err != nil { response.FailWithMessage("获取UGC模组信息失败: "+err.Error(), ctx) return } response.OkWithData(workshopItemDetails, ctx) } // DeleteUgcModFile 删除UGC模组文件 // @Summary 删除UGC模组文件 // @Description 删除UGC模组文件 // @Tags mod // @Accept json // @Produce json // @Param levelName query string true "世界名称" // @Param workshopId query string true "WorkshopID" // @Success 200 {object} response.Response // @Router /api/mod/ugc [delete] func (h *ModHandler) DeleteUgcModFile(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) levelName := ctx.Query("levelName") workshopId := ctx.Query("workshopId") err := h.modService.DeleteUgcModFile(clusterName, levelName, workshopId) if err != nil { response.FailWithMessage("删除失败: "+err.Error(), ctx) return } response.OkWithMessage("删除成功", ctx) } ================================================ FILE: internal/api/handler/player_handler.go ================================================ package handler import ( "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/service/game" "dst-admin-go/internal/service/player" "net/http" "github.com/gin-gonic/gin" ) type PlayerHandler struct { playerService *player.PlayerService gameProcess game.Process } func NewPlayerHandler(playerService *player.PlayerService, gameProcess game.Process) *PlayerHandler { return &PlayerHandler{ playerService: playerService, gameProcess: gameProcess, } } func (p *PlayerHandler) GetPlayerList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) ctx.JSON(http.StatusOK, gin.H{ "code": 200, "msg": "success", "data": p.playerService.GetPlayerList(clusterName, "Master", p.gameProcess), }) } func (p *PlayerHandler) GetPlayerAllList(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) ctx.JSON(http.StatusOK, gin.H{ "code": 200, "msg": "success", "data": p.playerService.GetPlayerAllList(clusterName, p.gameProcess), }) } func (p *PlayerHandler) RegisterRoute(router *gin.RouterGroup) { player := router.Group("/api/game/8level/players") { player.GET("", p.GetPlayerList) player.GET("/all", p.GetPlayerAllList) } } ================================================ FILE: internal/api/handler/player_log_handler.go ================================================ package handler import ( "dst-admin-go/internal/database" "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/response" "fmt" "log" "net/http" "strconv" "github.com/gin-gonic/gin" ) type PlayerLogHandler struct { } func NewPlayerLogHandler() *PlayerLogHandler { return &PlayerLogHandler{} } func (l *PlayerLogHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/player/log", l.PlayerLogQueryPage) router.POST("/api/player/log/delete", l.DeletePlayerLog) router.GET("/api/player/log/delete/all", l.DeletePlayerLogAll) } // PlayerLogQueryPage 生成 swagger 文档注释 // @Summary 分页查询玩家日志 // @Description 分页查询玩家日志 // @Tags playerLog // @Param name query string false "玩家名称" // @Param kuId query string false "KuId" // @Param steamId query string false "SteamId" // @Param role query string false "角色" // @Param action query string false "操作" // @Param ip query string false "IP地址" // @Param page query int false "页码" default(1) // @Param size query int false "每页数量" default(10) // @Success 200 {object} response.Response // @Router /api/player/log [get] func (l *PlayerLogHandler) PlayerLogQueryPage(ctx *gin.Context) { //获取查询参数 //name := ctx.Query("name") //kuId := ctx.Query("kuId") //steamId := ctx.Query("steamId") //role := ctx.Query("role") //action := ctx.Query("action") page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1")) size, _ := strconv.Atoi(ctx.DefaultQuery("size", "10")) if page <= 0 { page = 1 } if size < 0 { size = 10 } db := database.Db db2 := database.Db if name, isExist := ctx.GetQuery("name"); isExist { db = db.Where("name LIKE ?", "%"+name+"%") db2 = db2.Where("name LIKE ?", "%"+name+"%") } if kuId, isExist := ctx.GetQuery("kuId"); isExist { db = db.Where("ku_id LIKE ?", "%"+kuId+"%") db2 = db2.Where("ku_id LIKE ?", "%"+kuId+"%") } if steamId, isExist := ctx.GetQuery("steamId"); isExist { db = db.Where("steamId LIKE ?", "%"+steamId+"%") db2 = db2.Where("steamId LIKE ?", "%"+steamId+"%") } if role, isExist := ctx.GetQuery("role"); isExist { db = db.Where("role LIKE ?", "%"+role+"%") db2 = db2.Where("role LIKE ?", "%"+role+"%") } if action, isExist := ctx.GetQuery("action"); isExist { db = db.Where("action LIKE ?", "%"+action+"%") db2 = db2.Where("action LIKE ?", "%"+action+"%") } if ip, isExist := ctx.GetQuery("ip"); isExist { db = db.Where("ip LIKE ?", "%"+ip+"%") db2 = db2.Where("ip LIKE ?", "%"+ip+"%") } db = db.Order("created_at desc").Limit(size).Offset((page - 1) * size) playerLogs := make([]model.PlayerLog, 0) if err := db.Find(&playerLogs).Error; err != nil { fmt.Println(err.Error()) } var total int64 db2.Model(&model.PlayerLog{}).Count(&total) totalPages := total / int64(size) if total%int64(size) != 0 { totalPages++ } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: response.Page{ Data: playerLogs, Page: page, Size: size, Total: total, TotalPages: totalPages, }, }) } // DeletePlayerLog 删除玩家日志 // @Summary 删除玩家日志 // @Description 删除玩家日志 // @Tags playerLog // @Param ids body []int64 true "ID列表" // @Success 200 {object} response.Response // @Router /api/player/log/delete [post] func (l *PlayerLogHandler) DeletePlayerLog(ctx *gin.Context) { var payload struct { Ids []int64 `json:"ids"` } err := ctx.ShouldBind(&payload) if err != nil { log.Panicln(err) } db := database.Db db.Delete(&model.PlayerLog{}, payload.Ids) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: nil, }) } // DeletePlayerLogAll 删除所有玩家日志 // @Summary 删除所有玩家日志 // @Description 删除所有玩家 // @Tags playerLog // @Success 200 {object} response.Response // @Router /api/player/log/delete/all [get] func (l *PlayerLogHandler) DeletePlayerLogAll(ctx *gin.Context) { db := database.Db db.Delete(&model.PlayerLog{}) // 删除所有记录 result := db.Where("1 = 1").Delete(&model.PlayerLog{}) if result.Error != nil { log.Panicln(result.Error) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: nil, }) } ================================================ FILE: internal/api/handler/statistics_handler.go ================================================ package handler import ( "dst-admin-go/internal/database" "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/pkg/utils" "fmt" "log" "net/http" "time" "github.com/gin-gonic/gin" ) type StatisticsHandler struct { } func NewStatisticsHandler() *StatisticsHandler { return &StatisticsHandler{} } type UserStatistics struct { Count int `json:"y"` Date time.Time `json:"x"` } type TopStatistics struct { Id int `json:"id"` Count int `json:"count"` Name string `json:"name"` KuId string `json:"kuId"` SteamId string `json:"steamId"` Role string `json:"role"` ActionDesc string `json:"actionDesc"` CreatedAt string `json:"createdAt"` } type RoleRateStatistics struct { Role string `json:"role"` Count int `json:"count"` } func findStamp(stamp int64, data []UserStatistics) *UserStatistics { for _, d := range data { unix := utils.Bod(d.Date).UnixMilli() if unix == stamp { return &d } } return nil } func (s *StatisticsHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/statistics/active/user", s.CountActiveUser) router.GET("/api/statistics/top/death", s.TopDeaths) router.GET("/api/statistics/top/login", s.TopUserLoginimes) router.GET("/api/statistics/top/active", s.TopUserActiveTimes) router.GET("/api/statistics/rate/role", s.CountRoleRate) router.GET("/api/statistics/regenerate", s.LastThNRegenerate) } func (s *StatisticsHandler) CountActiveUser(ctx *gin.Context) { unit := ctx.Query("unit") startDate := startDate(ctx) endDate := endDate(ctx) log.Println("unit", unit, "startTime", startDate, "endTime", endDate) db := database.Db var data1 []UserStatistics var data2 []UserStatistics var stamps []int64 //database.Raw("select count(distinct name), day(create_at) from player_logs where create_at between ? and ? group by month(create_at), day(create_at)", "2023-02-25T16:24:33.2960449+08:00", "2023-02-25T15:59:15.5348647+08:00").Scan(&data) if unit == "MONTH" { db.Raw("select count(distinct name) as count,created_at as date from player_logs where created_at between ? and ? group by strftime('%Y',created_at),strftime('%m',created_at)", startDate, endDate).Scan(&data1) db.Raw("select count(name) as count,created_at as date from player_logs where created_at between ? and ? and action like '[JoinAnnouncement]' group by strftime('%Y',created_at),strftime('%m',created_at)", startDate, endDate).Scan(&data2) } if unit == "DAY" { sql1 := ` select count(distinct name) as count,created_at as date from player_logs where created_at between ? and ? group by strftime('%m',created_at),strftime('%d',created_at) ` sql2 := ` select count(name) as count,created_at as date from player_logs where created_at between ? and ? and action like '[JoinAnnouncement]' group by strftime('%m',created_at),strftime('%d',created_at) ` db.Raw(sql1, startDate, endDate).Scan(&data1) db.Raw(sql2, startDate, endDate).Scan(&data2) // database.Raw("select count(distinct name) as count,created_at as date from player_logs where action like '[JoinAnnouncement]' group by strftime('%m',created_at),strftime('%d',created_at)").Scan(&data1) // database.Raw("select count(name) as count,created_at as date from player_logs where action like '[JoinAnnouncement]' group by strftime('%m',created_at),strftime('%d',created_at)").Scan(&data2) stamps = utils.Get_stamp_day(startDate, endDate) } var axis struct { X []int64 `json:"x"` Y1 []int `json:"y1"` Y2 []int `json:"y2"` } log.Println("data1", data1) log.Println("data1", data2) //填充数据 // var stamp []int64; for _, stamp := range stamps { axis.X = append(axis.X, stamp) if d := findStamp(stamp, data1); d != nil { axis.Y1 = append(axis.Y1, d.Count) } else { axis.Y1 = append(axis.Y1, 0) } if d := findStamp(stamp, data2); d != nil { axis.Y2 = append(axis.Y2, d.Count) } else { axis.Y2 = append(axis.Y2, 0) } } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: axis, }) } func (s *StatisticsHandler) CountLoginUser(ctx *gin.Context) { unit := ctx.Query("unit") startDate := startDate(ctx) endDate := endDate(ctx) fmt.Println("unit", unit, "startTime", startDate, "endTime", endDate) db := database.Db var data []UserStatistics if unit == "MONTH" { db.Raw("select count(name) as count,created_at as date from player_logs where created_at between ? and ? group by strftime('%Y',created_at),strftime('%m',created_at)", startDate, endDate).Scan(&data) } if unit == "DAY" { db.Raw("select count(name) as count,created_at as date from player_logs where created_at between ? and ? group by strftime('%m',created_at),strftime('%d',created_at)", startDate, endDate).Scan(&data) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: data, }) } func (s *StatisticsHandler) TopUserActiveTimes(ctx *gin.Context) { N := ctx.Query("N") // startTime, _ := time.Parse("2006-01-02T15:04:05.000Z", startDate) // endTime, _ := time.Parse("2006-01-02T15:04:05.000Z", endDate) startDate := startDate(ctx) endDate := endDate(ctx) fmt.Println("N", N, "startTime", startDate, "endTime", endDate) db := database.Db //本天,本周,本月 var data []TopStatistics sql := ` select max(id) as id,count(name) as count, name, ku_id, steam_id, role, action_desc, created_at from player_logs where created_at between ? and ? and action like '[JoinAnnouncement]' group by name order by count(id) DESC limit ? ` db.Raw(sql, startDate, endDate, N).Scan(&data) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: data, }) } func (s *StatisticsHandler) TopUserLoginimes(ctx *gin.Context) { N := ctx.Query("N") startDate := startDate(ctx) endDate := endDate(ctx) fmt.Println("N", N, "startDate", startDate, "endDate", endDate) db := database.Db //本天,本周,本月 var data []TopStatistics sql := ` select max(p.id) as id,count(p.name) as count, p.name, c.ku_id, c.steam_id, role, action_desc, p.created_at from player_logs p left join connects c on p.name = c.name where p.created_at between ? and ? and p.action like '[JoinAnnouncement]' group by p.name order by count(p.id) DESC limit ? ` db.Raw(sql, startDate, endDate, N).Scan(&data) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: data, }) } func (s *StatisticsHandler) TopDeaths(ctx *gin.Context) { N := ctx.Query("N") startDate := startDate(ctx) endDate := endDate(ctx) fmt.Println("N", N, "startDate", startDate, "endDate", endDate) db := database.Db //本天,本周,本月 var data []TopStatistics sql := ` select max(id) as id, count(id) as count, name, ku_id, steam_id, role, action_desc, created_at from player_logs where created_at between ? and ? and action like '[DeathAnnouncement]' group by name order by count(id) DESC limit ? ` db.Raw(sql, startDate, endDate, N).Scan(&data) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: data, }) } func (s *StatisticsHandler) CountRoleRate(ctx *gin.Context) { startDate := startDate(ctx) endDate := endDate(ctx) db := database.Db //本天,本周,本月 var data []RoleRateStatistics sql := ` select role as role, count(distinct name) as count from player_logs where role != '' and created_at between ? and ? group by role ` db.Raw(sql, startDate, endDate).Scan(&data) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: data, }) } func startDate(ctx *gin.Context) time.Time { var date time.Time if t, isExist := ctx.GetQuery("startDate"); isExist { date, _ = time.Parse("2006-01-02T15:04:05.000Z", t) } return date } func endDate(ctx *gin.Context) time.Time { var date time.Time if t, isExist := ctx.GetQuery("endDate"); isExist { date, _ = time.Parse("2006-01-02T15:04:05.000Z", t) } return date } func (s *StatisticsHandler) LastThNRegenerate(ctx *gin.Context) { N := ctx.Query("N") db := database.Db //本天,本周,本月 var data []model.Regenerate sql := ` select * from regenerates order by created_at DESC limit ? ` db.Raw(sql, N).Scan(&data) ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "success", Data: data, }) } ================================================ FILE: internal/api/handler/update.go ================================================ package handler import ( "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/update" "log" "net/http" "github.com/gin-gonic/gin" ) type UpdateHandler struct { updateService update.Update } func NewUpdateHandler(update update.Update) *UpdateHandler { return &UpdateHandler{ updateService: update, } } func (h *UpdateHandler) RegisterRoute(router *gin.RouterGroup) { router.GET("/api/game/update", h.Update) } // Update 生成 swagger 文档注释 // @Summary 更新游戏 // @Description 更新游戏 // @Tags update // @Success 200 {object} response.Response // @Router /api/game/update [get] func (h *UpdateHandler) Update(ctx *gin.Context) { clusterName := context.GetClusterName(ctx) err := h.updateService.Update(clusterName) if err != nil { log.Panicln("更新游戏失败: ", err) } ctx.JSON(http.StatusOK, response.Response{ Code: 200, Msg: "update dst success", Data: nil, }) } ================================================ FILE: internal/api/router.go ================================================ package api import ( "dst-admin-go/internal/api/handler" "dst-admin-go/internal/collect" "dst-admin-go/internal/config" "dst-admin-go/internal/middleware" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/backup" "dst-admin-go/internal/service/dstConfig" "dst-admin-go/internal/service/dstMap" "dst-admin-go/internal/service/game" "dst-admin-go/internal/service/gameArchive" "dst-admin-go/internal/service/gameConfig" "dst-admin-go/internal/service/level" "dst-admin-go/internal/service/levelConfig" "dst-admin-go/internal/service/login" "dst-admin-go/internal/service/mod" "dst-admin-go/internal/service/player" "dst-admin-go/internal/service/update" "time" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/memstore" "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" "github.com/swaggo/gin-swagger" "gorm.io/gorm" ) func NewRoute(cfg *config.Config, db *gorm.DB) *gin.Engine { app := gin.Default() store := memstore.NewStore([]byte("secret")) store.Options(sessions.Options{ Path: "/", MaxAge: int(60 * 24 * 7 * time.Minute.Seconds()), HttpOnly: true, }) app.Use(sessions.Sessions("token", store)) app.Use(middleware.Recover) app.GET("/hello", func(ctx *gin.Context) { ctx.String(200, "Hello! Dont starve together") }) // Swagger UI app.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) RegisterStaticFile(app) Register(cfg, db, app.Group("")) return app } func initCollectors(archive *archive.PathResolver, dstConfigService dstConfig.Config) { getDstConfig, err := dstConfigService.GetDstConfig("MyDediServer") if err != nil { return } clusterName := getDstConfig.Cluster newCollect := collect.NewCollect(archive.ClusterPath(clusterName), clusterName) collect.Collector = newCollect collect.Collector.StartCollect() } func RegisterStaticFile(app *gin.Engine) { defer func() { if r := recover(); r != nil { } }() app.Use(func(context *gin.Context) { context.Writer.Header().Set("Cache-Control", "public, max-age=30672000") }) app.LoadHTMLGlob("dist/index.html") // 添加入口index.html //r.LoadHTMLFiles("dist//*") // 添加资源路径 app.Static("/assets", "./dist/assets") app.Static("/misc", "./dist/misc") app.Static("/static/js", "./dist/static/js") // 添加资源路径 app.Static("/static/css", "./dist/static/css") // 添加资源路径 app.Static("/static/img", "./dist/static/img") // 添加资源路径 app.Static("/static/fonts", "./dist/static/fonts") // 添加资源路径 app.Static("/static/media", "./dist/static/media") // 添加资源路径 app.StaticFile("/favicon.ico", "./dist/favicon.ico") // 添加资源路径 app.StaticFile("/asset-manifest.json", "./dist/asset-manifest.json") // 添加资源路径 app.StaticFile("/", "./dist/index.html") } func Register(cfg *config.Config, db *gorm.DB, router *gin.RouterGroup) { // service dstConfigService := dstConfig.NewDstConfig(db) updateService := update.NewUpdateService(dstConfigService) resolverService, _ := archive.NewPathResolver(dstConfigService) loginService := login.NewLoginService(cfg) levelConfigUtils := levelConfig.NewLevelConfigUtils(resolverService) gameProcess := game.NewGame(dstConfigService, levelConfigUtils) gameConfigService := gameConfig.NewGameConfig(resolverService, levelConfigUtils) backupService := backup.NewBackupService(resolverService, dstConfigService, gameProcess) levelService := level.NewLevelService(gameProcess, dstConfigService, resolverService, levelConfigUtils) playerService := player.NewPlayerService(resolverService) gameArchiveService := gameArchive.NewGameArchive(gameConfigService, levelService, resolverService) modService := mod.NewModService(db, dstConfigService, resolverService) dstMapGenerator := dstMap.NewDSTMapGenerator() // init initCollectors(resolverService, dstConfigService) // handler updateHandler := handler.NewUpdateHandler(updateService) gameHandler := handler.NewGameHandler(gameProcess, levelService, gameArchiveService, levelConfigUtils, resolverService) gameConfigHandler := handler.NewGameConfigHandler(gameConfigService) dstConfigHandler := handler.NewDstConfigHandler(dstConfigService, resolverService) loginHandler := handler.NewLoginHandler(loginService) backupHandler := handler.NewBackupHandler(backupService) levelHandler := handler.NewLevelHandler(levelService) playerHandler := handler.NewPlayerHandler(playerService, gameProcess) levelLogHandler := handler.NewLevelLogHandler(resolverService) kvHandler := handler.NewKvHandler(db) dstApiHandler := handler.NewDstApiHandler() dstMapHandler := handler.NewDstMapHandler(resolverService, dstMapGenerator) playerLogHandler := handler.NewPlayerLogHandler() statisticsHandler := handler.NewStatisticsHandler() modHandler := handler.NewModHandler(modService, dstConfigService) // 中间件 router.Use(middleware.Authentication(loginService)) router.Use(middleware.ClusterMiddleware(dstConfigService)) // route updateHandler.RegisterRoute(router) gameHandler.RegisterRoute(router) gameConfigHandler.RegisterRoute(router) dstConfigHandler.RegisterRoute(router) loginHandler.RegisterRoute(router) backupHandler.RegisterRoute(router) levelHandler.RegisterRoute(router) playerHandler.RegisterRoute(router) levelLogHandler.RegisterRoute(router) kvHandler.RegisterRoute(router) dstApiHandler.RegisterRoute(router) dstMapHandler.RegisterRoute(router) playerLogHandler.RegisterRoute(router) statisticsHandler.RegisterRoute(router) modHandler.RegisterRoute(router) } ================================================ FILE: internal/collect/collect.go ================================================ package collect import ( "dst-admin-go/internal/database" "dst-admin-go/internal/model" "fmt" "log" "path/filepath" "regexp" "strings" "time" "github.com/hpcloud/tail" ) var Collector *Collect type Collect struct { state chan int stop chan bool severLogList []string serverChatLogList []string length int clusterName string } func NewCollect(baseLogPath string, clusterName string) *Collect { collect := &Collect{ state: make(chan int, 1), severLogList: []string{ filepath.Join(baseLogPath, "Master", "server_log.txt"), }, serverChatLogList: []string{ filepath.Join(baseLogPath, "Master", "server_chat_log.txt"), }, stop: make(chan bool, 2), length: 2, clusterName: clusterName, } collect.state <- 1 return collect } func (c *Collect) Stop() { close(c.stop) } func (c *Collect) ReCollect(baseLogPath, clusterName string) { for i := 0; i < c.length; i++ { c.stop <- true } c.severLogList = []string{ filepath.Join(baseLogPath, "Master", "server_log.txt"), } c.serverChatLogList = []string{ filepath.Join(baseLogPath, "Master", "server_chat_log.txt"), } c.clusterName = clusterName c.state <- 1 } func (c *Collect) StartCollect() { go func() { for { select { case <-c.state: // 采集 for _, s := range c.severLogList { go c.tailServeLog(s) } for _, s := range c.serverChatLogList { go c.tailServerChatLog(s) } default: time.Sleep(5 * time.Second) continue } } }() } func (c *Collect) parseSpawnRequestLog(text string) { defer func() { if r := recover(); r != nil { log.Printf("Spawn request Log text: %s\n", text) log.Printf("玩家角色日志解析异常: %v\n", r) } }() // 捕获 (1)时间, (2)动作, (3)角色, (4)玩家名 re := regexp.MustCompile(`^\[([^\]]+)\]:\s*(.*?):\s*(\w+)\s*from\s*(.+)$`) matches := re.FindStringSubmatch(text) if len(matches) != 5 { // 如果日志格式不匹配,直接退出 log.Printf("Spawn request 日志格式不匹配: %s\n", text) return } t := matches[1] // 00:37:41 // action := matches[2] // Spawn request role := matches[3] // winona name := strings.TrimSpace(matches[4]) spawn := model.Spawn{Name: name, Role: role, Time: t, ClusterName: c.clusterName} if err := database.Db.Create(&spawn).Error; err != nil { log.Printf("插入玩家 Spawn 日志失败: %v\n", err) } } func (c *Collect) parseRegenerateLog(text string) { defer func() { if err := recover(); err != nil { log.Println("Generating 日志解析异常:", err) } }() regenerate := model.Regenerate{ ClusterName: c.clusterName, } database.Db.Create(®enerate) } func (c *Collect) parseNewIncomingLog(lines []string) { defer func() { if err := recover(); err != nil { log.Println("new incoming 日志解析异常:", err) } }() connect := model.Connect{} log.Println("len:", len(lines), lines) for i, line := range lines { if i == 1 { // 解析 ip str := strings.Split(line, " ") if len(str) < 5 { log.Println("ip 解析错误: ", line) connect.Ip = "" } else { var ip string if strings.Contains(line, "[LAN]") { ip = str[5] } else { ip = str[4] } connect.Ip = ip fmt.Println("ip", ip) } } if i == 2 { // 解析 ip } if i == 3 { // 解析 KuId 和 用户名 str := strings.Split(line, " ") if len(str) <= 4 { log.Println("kuid 解析错误: ", line) } else { ku := str[3] ku = ku[1 : len(ku)-1] name := str[4] connect.Name = name connect.KuId = ku fmt.Println("ku", ku, "name", name) } } if i == 4 { // 解析 steamId str := strings.Split(line, " ") if len(str) < 4 { log.Println("steamid 解析错误: ", line) } else { steamId := str[4] steamId = steamId[1 : len(steamId)-1] fmt.Println("steamId", steamId) connect.SteamId = steamId connect.ClusterName = c.clusterName } } if strings.Contains(line, "Resuming user:") { // 解析 session file path str := strings.Split(line, " ") log.Println(len(str), lines) //[00:14:37]: Resuming user: session/7477D5E4A0424844/KU_Mt-zrX8K_ if len(str) < 4 { log.Println("session file path 解析错误: ", line) } else { name := str[3] name = strings.Replace(name, "session/", "", -1) connect.SessionFile = name } } // [03:19:10]: Serializing user: session/D480EA2CEF7633C0/KU_Mt-zrX8K_/0000000005 if strings.Contains(line, "Serializing user:") { // 解析 session file path str := strings.Split(line, " ") log.Println(len(str), lines) //[00:14:37]: Resuming user: session/7477D5E4A0424844/KU_Mt-zrX8K_ if len(str) < 4 { log.Println("session file path 解析错误: ", line) } else { name := str[3] name = strings.Replace(name, "session/", "", -1) connect.SessionFile = name } } } database.Db.Create(&connect) } func (c *Collect) tailServeLog(fileName string) { log.Println("开始采集 path:", fileName) config := tail.Config{ ReOpen: true, // 重新打开 Follow: true, // 是否跟随 Location: &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读 MustExist: false, // 文件不存在不报错 Poll: true, } tails, err := tail.TailFile(fileName, config) if err != nil { log.Println("文件监听失败", err) } var ( which = 0 isNewConnect = false incoming []string ) for { select { case line, ok := <-tails.Lines: if !ok { log.Println("文件读取失败", err) time.Sleep(time.Second) } else { text := line.Text if find := strings.Contains(text, "Spawn request"); find { c.parseSpawnRequestLog(text) } else if find := strings.Contains(text, "# Generating"); find { c.parseRegenerateLog(text) } else if find := strings.Contains(text, "New incoming connection"); find { isNewConnect = true } // 获取接下来的五条数据 if isNewConnect { incoming = append(incoming, text) which++ if which > 10 { isNewConnect = false which = 0 c.parseNewIncomingLog(incoming) incoming = []string{} } } } case <-c.stop: // 结束监听 err := tails.Stop() if err != nil { log.Println("tail log 结束失败") return } return } } } func (c *Collect) parseChatLog(text string) { defer func() { if err := recover(); err != nil { log.Println("玩家行为日志解析异常:", err) } }() //[00:00:55]: [Join Announcement] 猜猜我是谁 if strings.Contains(text, "[Join Announcement]") { c.parseJoin(text) } //[00:02:28]: [Leave Announcement] 猜猜我是谁 if strings.Contains(text, "[Leave Announcement]") { c.parseLeave(text) } //[00:02:17]: [Death Announcement] 猜猜我是谁 死于: 采摘的红蘑菇。她变成了可怕的鬼魂! if strings.Contains(text, "[Death Announcement]") { c.parseDeath(text) } //[00:02:37]: [Resurrect Announcement] 猜猜我是谁 复活自: TMIP 控制台. if strings.Contains(text, "[Resurrect Announcement]") { c.parseResurrect(text) } //[00:03:16]: [Say] (KU_Mt-zrX8K) 猜猜我是谁: 你好啊 if strings.Contains(text, "[Say]") { c.parseSay(text) } //[10:01:42]: [Announcement] 欢迎访客歪比巴卜,游玩 if strings.Contains(text, "[Announcement]") { c.parseAnnouncement(text) } } func (c *Collect) parseSay(text string) { fmt.Println(text) // 正则解析日志 re := regexp.MustCompile(`\[(.*?)\]: (\[.*?\]) \((.*?)\) (.*?): (.*)`) matches := re.FindStringSubmatch(text) if len(matches) != 6 { fmt.Println("无法解析日志:", text, matches) return } // 时间 t := matches[1] // [Say] action := matches[2] kuId := matches[3] // 玩家名字,可包含空格 name := matches[4] actionDesc := matches[5] // 获取玩家角色和连接信息 spawn := c.getSpawnRole(name) connect := c.getConnectInfo(name) playerLog := model.PlayerLog{ Name: name, Role: spawn.Role, Action: action, ActionDesc: actionDesc, Time: t, Ip: connect.Ip, KuId: kuId, SteamId: connect.SteamId, ClusterName: c.clusterName, } // 保存到数据库,并打印错误 if err := database.Db.Create(&playerLog).Error; err != nil { fmt.Println("插入玩家日志失败:", err) } } func (c *Collect) parseResurrect(text string) { c.parseDeath(text) } func (c *Collect) parseDeath(text string) { fmt.Println(text) // 正则表达式 (1)时间, (2)动作, (3)剩余所有内容 re := regexp.MustCompile(`^\[([^\]]+)\]:\s*(\[[^\]]+\])\s*(.*)$`) matches := re.FindStringSubmatch(text) if len(matches) != 4 { log.Println("无法解析 Announcement Log (正则不匹配):", text) return } t := matches[1] action := matches[2] // 擦屁股 action = strings.ReplaceAll(action, " ", "") rest := strings.TrimSpace(matches[3]) // 名字 + 描述 整体 var name string var actionDesc string // 死亡/复活的分隔符列表 (支持中英文) // 关键:在 Death Announce 和 Resurrect Announce 之间寻找共同的分隔模式 // 中文:死于: / 复活自: // 英文:died from / resurrected from / revived by announcementWords := []string{ "死于:", "died from", "was killed by", "starved", "suicide", // 死亡 "复活自:", "resurrected from", "revived by", // 复活 } splitIndex := -1 for _, word := range announcementWords { // 查找分隔符 idx := strings.Index(rest, word) if idx > splitIndex { // 找到最靠前的已知分隔符 splitIndex = idx // 找到后立即退出循环,因为第一个匹配就是名字和描述的边界 break } } if splitIndex != -1 { // 找到了分隔符:分割 rest name = strings.TrimSpace(rest[:splitIndex]) actionDesc = strings.TrimSpace(rest[splitIndex:]) } else { // 未找到已知分隔符,假设整个 rest 都是名字,描述为空 (适用于名字很长,或系统消息) name = rest actionDesc = "" fmt.Println("Announcement Log 未找到分隔符,将全部分配给 Name:", name) } spawn := c.getSpawnRole(name) connect := c.getConnectInfo(name) fmt.Println(connect) playerLog := model.PlayerLog{ Name: name, Role: spawn.Role, Action: action, ActionDesc: actionDesc, Time: t, Ip: connect.Ip, KuId: connect.KuId, SteamId: connect.SteamId, ClusterName: c.clusterName, } if err := database.Db.Create(&playerLog).Error; err != nil { fmt.Println("插入玩家日志失败:", err) } } func (c *Collect) parseLeave(text string) { c.parseJoin(text) } func (c *Collect) parseJoin(text string) { fmt.Println(text) // 正则表达式:捕获 (1)时间, (2)动作, (3)玩家名 re := regexp.MustCompile(`^\[([^\]]+)\]:\s*(\[[^\]]+\])\s*(.+)$`) matches := re.FindStringSubmatch(text) // 预期匹配 4 组:[完整匹配, 时间, 动作, 玩家名] if len(matches) != 4 { log.Println("无法解析 Join Log (正则不匹配):", text) return } // 捕获结果 t := matches[1] // 时间: 00:01:43 action := matches[2] // 动作: [Join Announcement] // 擦屁股 action = strings.ReplaceAll(action, " ", "") // 玩家名字是捕获组 3,使用 strings.TrimSpace 确保名字前后没有多余空格 name := strings.TrimSpace(matches[3]) spawn := c.getSpawnRole(name) connect := c.getConnectInfo(name) playerLog := model.PlayerLog{ Name: name, Role: spawn.Role, Action: action, Time: t, Ip: connect.Ip, KuId: connect.KuId, SteamId: connect.SteamId, ClusterName: c.clusterName, } // 保存到数据库,并打印错误 if err := database.Db.Create(&playerLog).Error; err != nil { fmt.Println("插入玩家日志失败:", err) } } func (c *Collect) tailServerChatLog(fileName string) { log.Println("开始采集 path:", fileName) config := tail.Config{ ReOpen: true, // 重新打开 Follow: true, // 是否跟随 Location: &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读 MustExist: false, // 文件不存在不报错 Poll: true, } tails, err := tail.TailFile(fileName, config) if err != nil { log.Println("文件监听失败", err) } for { select { case line, ok := <-tails.Lines: if !ok { log.Println("文件读取失败", err) time.Sleep(time.Second) } else { text := line.Text c.parseChatLog(text) } case <-c.stop: // 结束监听 err := tails.Stop() if err != nil { log.Println("tail log 结束失败") return } return } } } func (c *Collect) getSpawnRole(name string) *model.Spawn { spawn := new(model.Spawn) database.Db.Where("name LIKE ? and cluster_name = ?", "%"+name+"%", c.clusterName).Last(spawn) return spawn } func (c *Collect) getConnectInfo(name string) *model.Connect { connect := new(model.Connect) database.Db.Where("name LIKE ? and cluster_name = ?", "%"+name+"%", c.clusterName).Last(connect) return connect } func (c *Collect) parseAnnouncement(text string) { fmt.Println(text) // 正则解析日志 re := regexp.MustCompile(`\[(.*?)\]: (\[Announcement\]) (.*)`) matches := re.FindStringSubmatch(text) // 无法解析宣告日志: 00:55:21 Announcement test if len(matches) != 4 { fmt.Println("无法解析宣告日志:", text, matches) return } // 时间 t := matches[1] // [Announcement] action := matches[2] // 宣告的内容 actionDesc := matches[3] playerLog := model.PlayerLog{ Name: "-", Role: "-", Action: action, ActionDesc: actionDesc, Time: t, Ip: "-", KuId: "-", SteamId: "-", ClusterName: c.clusterName, } // 保存到数据库,并打印错误 if err := database.Db.Create(&playerLog).Error; err != nil { fmt.Println("插入玩家日志失败:", err) } } ================================================ FILE: internal/collect/collect_map.go ================================================ package collect import ( "dst-admin-go/internal/service/archive" "sync" ) var CollectorMap *CollectMap type CollectMap struct { cache sync.Map archive *archive.PathResolver } func NewCollectMap() *CollectMap { return &CollectMap{ cache: sync.Map{}, } } func (cm *CollectMap) AddNewCollect(clusterName string, baseLogPath string) { _, ok := cm.cache.Load(clusterName) if !ok { collect := NewCollect(baseLogPath, clusterName) collect.StartCollect() cm.cache.Store(clusterName, collect) } } func (cm *CollectMap) RemoveCollect(clusterName string) { value, loaded := cm.cache.LoadAndDelete(clusterName) if loaded { value.(*Collect).Stop() } } ================================================ FILE: internal/config/config.go ================================================ package config import ( "fmt" "io/ioutil" "gopkg.in/yaml.v3" ) type Config struct { BindAddress string `yaml:"bindAddress"` Port string `yaml:"port"` Path string `yaml:"path"` Db string `yaml:"database"` SteamAPIKey string `yaml:"steamAPIKey"` Flag string `yaml:"flag"` WanIP string `yaml:"wanip"` WhiteAdminIP string `yaml:"whiteadminip"` Token string `yaml:"token"` AutoUpdateModinfo struct { Enable bool `yaml:"enable"` CheckInterval int `yaml:"checkInterval"` UpdateCheckInterval int `yaml:"updateCheckInterval"` } `yaml:"autoUpdateModinfo"` } const ( ConfigPath = "./config.yml" DefaultPort = "8083" ) var Cfg *Config func Load() *Config { yamlFile, err := ioutil.ReadFile(ConfigPath) if err != nil { fmt.Println(err.Error()) } var c *Config err = yaml.Unmarshal(yamlFile, &c) if err != nil { fmt.Println(err.Error()) } if c.Port == "" { c.Port = DefaultPort } if c.AutoUpdateModinfo.UpdateCheckInterval == 0 { c.AutoUpdateModinfo.UpdateCheckInterval = 10 } if c.AutoUpdateModinfo.CheckInterval == 0 { c.AutoUpdateModinfo.CheckInterval = 5 } Cfg = c return c } ================================================ FILE: internal/database/sqlite.go ================================================ package database import ( "dst-admin-go/internal/config" "dst-admin-go/internal/model" "log" "github.com/glebarez/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) var Db *gorm.DB func InitDB(config *config.Config) *gorm.DB { db, err := gorm.Open(sqlite.Open(config.Db), &gorm.Config{ Logger: logger.Default.LogMode(logger.Silent), }) if err != nil { panic("failed to connect database") } Db = db err = db.AutoMigrate( &model.Spawn{}, &model.PlayerLog{}, &model.Connect{}, &model.Regenerate{}, &model.ModInfo{}, &model.Cluster{}, &model.JobTask{}, &model.AutoCheck{}, &model.Announce{}, &model.WebLink{}, &model.BackupSnapshot{}, &model.LogRecord{}, &model.KV{}, ) if err != nil { log.Println("AutoMigrate error", err) } return db } ================================================ FILE: internal/middleware/auth.go ================================================ package middleware import ( "dst-admin-go/internal/service/login" "log" "net/http" "strings" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" ) var ( whitelist = []string{"/api/login", "/api/logout", "/ws", "/api/dst-static", "/api/init", "/api/install/steamcmd"} ) func apiFilter(s []string, str string) bool { //开放不是 /api 开头接口 if !strings.Contains(str, "/api") { return true } for _, v := range s { if v == str { return true } } return false } func Authentication(loginService *login.LoginService) gin.HandlerFunc { return func(c *gin.Context) { path := c.Request.URL.Path if apiFilter(whitelist, path) { c.Next() return } session := sessions.Default(c) username := session.Get("username") log.Println("username:", username) if username == nil { if loginService.IsWhiteIP(c) { loginService.DirectLogin(c) log.Println("white ip login", c.ClientIP()) c.Next() return } c.AbortWithStatus(http.StatusUnauthorized) } else { c.Next() } } } func SseHeadersMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Set("Content-Type", "text/event-stream") c.Writer.Header().Set("Cache-Control", "no-cache") c.Writer.Header().Set("Connection", "keep-alive") c.Writer.Header().Set("Transfer-Encoding", "chunked") c.Next() } } ================================================ FILE: internal/middleware/cluster.go ================================================ package middleware import ( "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/service/dstConfig" "net/http" "github.com/gin-gonic/gin" ) const ( clusterNameKey = "cluster_name" dstConfigKey = "dst_config" ) // ClusterMiddleware 从 HTTP Header 解析 cluster 名称并加载配置到 context func ClusterMiddleware(dstConfigService dstConfig.Config) gin.HandlerFunc { return func(c *gin.Context) { path := c.Request.URL.Path if apiFilter(whitelist, path) { c.Next() return } // 从 Header 获取集群名称 clusterName := c.GetHeader("Cluster") // 查询集群配置 config, err := dstConfigService.GetDstConfig(clusterName) if err != nil { c.JSON(http.StatusNotFound, response.Response{ Code: 500, Msg: "集群配置不存在: " + clusterName, }) c.Abort() return } // 将集群名称和配置注入到 context c.Set(clusterNameKey, config.Cluster) c.Set(dstConfigKey, config) c.Next() } } ================================================ FILE: internal/middleware/error.go ================================================ package middleware import ( "log" "net/http" "runtime/debug" "github.com/gin-gonic/gin" ) func Recover(c *gin.Context) { defer func() { if r := recover(); r != nil { //打印错误堆栈信息 log.Printf("panic: %v\n", r) debug.PrintStack() //封装通用json返回 //c.JSON(http.StatusOK, Result.Fail(errorToString(r))) //Result.Fail不是本例的重点,因此用下面代码代替 c.JSON(http.StatusOK, gin.H{ "code": "500", "msg": errorToString(r), "data": nil, }) //终止后续接口调用,不加的话recover到异常后,还会继续执行接口里后续代码 c.Abort() } }() //加载完 defer recover,继续后续接口调用 c.Next() } // recover错误,转string func errorToString(r interface{}) string { switch v := r.(type) { case error: return v.Error() default: return r.(string) } } ================================================ FILE: internal/middleware/start_before.go ================================================ package middleware import ( "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/levelConfig" "log" "path/filepath" "strings" "github.com/gin-gonic/gin" ) func StartBeforeMiddleware(archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) gin.HandlerFunc { return func(ctx *gin.Context) { makeRunVersion(ctx, archive, levelConfigUtils) customcommandsFile(ctx, archive, levelConfigUtils) } } func copyOsFile() { } func customcommandsFile(ctx *gin.Context, archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) { clusterName := context.GetClusterName(ctx) config, _ := levelConfigUtils.GetLevelConfig(clusterName) for _, item := range config.LevelList { levelName := item.File levelPath := archive.LevelPath(clusterName, levelName) path := filepath.Join(levelPath, "customcommands.lua") _ = fileUtils.CreateFileIfNotExists(path) customcommands, _ := fileUtils.ReadFile("./static/customcommands.lua") fileUtils.WriterTXT(path, customcommands) } } func makeRunVersion(ctx *gin.Context, archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) { clusterName := context.GetClusterName(ctx) version, _ := archive.GetLocalDstVersion(clusterName) urlPath := ctx.Request.URL.Path config, err := levelConfigUtils.GetLevelConfig(clusterName) if strings.Contains(urlPath, "all") { if err == nil { for i := range config.LevelList { config.LevelList[i].RunVersion = version config.LevelList[i].Version = version } } } else { levelName := ctx.Query("levelName") if err == nil { for i := range config.LevelList { if config.LevelList[i].File == levelName { config.LevelList[i].RunVersion = version config.LevelList[i].Version = version } } } } err = levelConfigUtils.SaveLevelConfig(clusterName, config) if err != nil { log.Println(err) } } ================================================ FILE: internal/model/LogRecord.go ================================================ package model import "gorm.io/gorm" type Action int const ( RUN Action = iota STOP NORMAL ) type LogRecord struct { gorm.Model Action Action `json:"action"` ClusterName string `json:"clusterName"` LevelName string `json:"levelName"` } ================================================ FILE: internal/model/announce.go ================================================ package model import "gorm.io/gorm" type Announce struct { gorm.Model Enable bool `json:"enable"` Frequency int64 `json:"frequency"` Interval int64 `json:"interval"` IntervalUnit string `json:"intervalUnit"` Method string `json:"method"` Content string `json:"content"` } ================================================ FILE: internal/model/autoCheck.go ================================================ package model import "gorm.io/gorm" type AutoCheck struct { gorm.Model Name string `json:"name"` ClusterName string `json:"clusterName"` LevelName string `json:"levelName"` Uuid string `json:"uuid"` Enable int `json:"enable"` Announcement string `json:"announcement"` Times int `json:"times"` Sleep int `json:"sleep"` Interval int `json:"interval"` CheckType string `json:"checkType"` } ================================================ FILE: internal/model/backup.go ================================================ package model import "gorm.io/gorm" type Backup struct { gorm.Model Name string `json:"name"` Description string `json:"description"` Path string `json:"Path"` Size string `json:"size"` Days string `json:"days"` Season bool `json:"season"` } ================================================ FILE: internal/model/backupSnapshot.go ================================================ package model import "gorm.io/gorm" type BackupSnapshot struct { gorm.Model Name string `json:"name"` Interval int `json:"interval"` MaxSnapshots int `json:"maxSnapshots"` Enable int `json:"enable"` IsCSave int `json:"isCSave"` } ================================================ FILE: internal/model/cluster.go ================================================ package model import "gorm.io/gorm" type Cluster struct { gorm.Model ClusterName string `gorm:"uniqueIndex" json:"clusterName"` Description string `json:"description"` SteamCmd string `json:"steamcmd"` ForceInstallDir string `json:"force_install_dir"` Backup string `json:"backup"` ModDownloadPath string `json:"mod_download_path"` Uuid string `json:"uuid"` Beta int `json:"beta"` Bin int `json:"bin"` Ugc_directory string `json:"ugc_directory"` Persistent_storage_root string `json:"persistent_storage_root"` Conf_dir string `json:"conf_dir"` } ================================================ FILE: internal/model/connect.go ================================================ package model import "gorm.io/gorm" type Connect struct { gorm.Model Ip string Name string KuId string SteamId string Time string ClusterName string SessionFile string } ================================================ FILE: internal/model/jobTask.go ================================================ package model import "gorm.io/gorm" type JobTask struct { gorm.Model ClusterName string `json:"clusterName"` LevelName string `json:"levelName"` Uuid string `json:"uuid"` Cron string `json:"cron"` Category string `json:"category"` Comment string `json:"comment"` Announcement string `json:"announcement"` Sleep int `json:"sleep"` Times int `json:"times"` Script int `json:"script"` } ================================================ FILE: internal/model/kv.go ================================================ package model import "gorm.io/gorm" type KV struct { gorm.Model Key string `json:"key"` Value string `json:"value"` } ================================================ FILE: internal/model/modInfo.go ================================================ package model import "gorm.io/gorm" type ModInfo struct { gorm.Model Auth string `json:"auth"` ConsumerAppid float64 `json:"consumer_appid"` CreatorAppid float64 `json:"creator_appid"` Description string `json:"description"` FileUrl string `json:"file_url"` Modid string `json:"modid"` Img string `json:"img"` LastTime float64 `json:"last_time"` ModConfig string `gorm:"TYPE:json" json:"mod_config"` Name string `json:"name"` V string `json:"v"` Update bool `json:"update"` } ================================================ FILE: internal/model/modKv.go ================================================ package model import "gorm.io/gorm" type ModKV struct { gorm.Model UserId string `json:"userId"` ModId int `json:"modId"` Config string `json:"config"` Version string `json:"version"` } ================================================ FILE: internal/model/model.go ================================================ // Package model defines the data models used by the application. package model ================================================ FILE: internal/model/playerLog.go ================================================ package model import "gorm.io/gorm" type PlayerLog struct { gorm.Model Name string `json:"name"` Role string `json:"role"` KuId string `json:"kuId"` SteamId string `json:"steamId"` Time string `json:"time"` Action string `json:"action"` ActionDesc string `json:"actionDesc"` Ip string `json:"ip"` ClusterName string `json:"clusterName"` } ================================================ FILE: internal/model/regenerate.go ================================================ package model import "gorm.io/gorm" type Regenerate struct { gorm.Model ClusterName string `json:"clusterName"` } ================================================ FILE: internal/model/spawnRole.go ================================================ package model import "gorm.io/gorm" type Spawn struct { gorm.Model Name string Role string Time string ClusterName string } ================================================ FILE: internal/model/webLink.go ================================================ package model import "gorm.io/gorm" type WebLink struct { gorm.Model Title string `json:"title"` Url string `json:"url"` Width string `json:"width"` Height string `json:"height"` } ================================================ FILE: internal/pkg/context/cluster.go ================================================ package context import ( "dst-admin-go/internal/service/dstConfig" "github.com/gin-gonic/gin" ) const ( clusterNameKey = "cluster_name" dstConfigKey = "dst_config" ) // GetClusterName 从 gin.Context 获取集群名称 // 需要配合 ClusterMiddleware 使用 func GetClusterName(c *gin.Context) string { if value, exists := c.Get(clusterNameKey); exists { if clusterName, ok := value.(string); ok { return clusterName } } return "" } // GetDstConfig 从 gin.Context 获取 DstConfig 对象 // 需要配合 ClusterMiddleware 使用 func GetDstConfig(c *gin.Context) *dstConfig.DstConfig { if value, exists := c.Get(dstConfigKey); exists { if config, ok := value.(dstConfig.DstConfig); ok { return &config } } return nil } ================================================ FILE: internal/pkg/response/response.go ================================================ package response import ( "net/http" "github.com/gin-gonic/gin" ) type Response struct { Code int `json:"code"` //提示代码 Msg string `json:"msg"` //提示信息 Data interface{} `json:"data"` //数据 } type Page struct { Data interface{} `json:"data"` Total int64 `json:"total"` TotalPages int64 `json:"totalPages"` Page int `json:"page"` Size int `json:"size"` } // OkWithData 成功响应带数据 func OkWithData(data interface{}, ctx *gin.Context) { ctx.JSON(http.StatusOK, Response{ Code: 200, Msg: "success", Data: data, }) } // OkWithMessage 成功响应带消息 func OkWithMessage(message string, ctx *gin.Context) { ctx.JSON(http.StatusOK, Response{ Code: 200, Msg: message, Data: nil, }) } // FailWithMessage 失败响应带消息 func FailWithMessage(message string, ctx *gin.Context) { ctx.JSON(http.StatusOK, Response{ Code: 500, Msg: message, Data: nil, }) } // OkWithPage 成功响应带分页数据 func OkWithPage(data interface{}, total, page, size int64, ctx *gin.Context) { totalPages := (total + size - 1) / size ctx.JSON(http.StatusOK, Response{ Code: 200, Msg: "success", Data: Page{ Data: data, Total: total, TotalPages: totalPages, Page: int(page), Size: int(size), }, }) } ================================================ FILE: internal/pkg/utils/collectionUtils/collectionUtils.go ================================================ package collectionUtils import "log" func ToSet(list []string) []string { var m = map[string]string{} var set []string for i, _ := range list { key := list[i] log.Println("key", key) _, ok := m[key] if !ok { m[key] = key set = append(set, key) } } return set } ================================================ FILE: internal/pkg/utils/dateUtils.go ================================================ package utils import ( "time" ) func Bod(t time.Time) time.Time { year, month, day := t.Date() return time.Date(year, month, day, 0, 0, 0, 0, t.Location()) } func Truncate(t time.Time) time.Time { return t.Truncate(24 * time.Hour) } func Get_stamp_day(start_time, end_time time.Time) (args []int64) { t1 := Bod(start_time) t2 := Bod(end_time) sInt := t1.UnixMilli() - 8*60*60*1000 eInt := t2.UnixMilli() - 8*60*60*1000 args = append(args, sInt) for { sInt += 86400 * 1000 if sInt > eInt { return } args = append(args, sInt) } } func Get_stamp_month(start_time, end_time time.Time) (args []int64) { t1 := Bod(start_time) t2 := Bod(end_time) sInt := t1.Unix() eInt := t2.Unix() args = append(args, sInt) for { sInt += 2592000000 if sInt > eInt { return } args = append(args, sInt) } } ================================================ FILE: internal/pkg/utils/dstUtils/dstUtils.go ================================================ package dstUtils import ( "bytes" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/dstConfig" "io/ioutil" "path/filepath" "regexp" "runtime" "strings" textTemplate "text/template" ) func EscapePath(path string) string { if runtime.GOOS == "windows" { return path } // 在这里添加需要转义的特殊字符 escapedChars := []string{" ", "'", "(", ")"} for _, char := range escapedChars { path = strings.ReplaceAll(path, char, "\\"+char) } return path } func WorkshopIds(content string) []string { var workshopIds []string re := regexp.MustCompile("\"workshop-\\w[-\\w+]*\"") workshops := re.FindAllString(content, -1) for _, workshop := range workshops { workshop = strings.Replace(workshop, "\"", "", -1) split := strings.Split(workshop, "-") workshopId := strings.TrimSpace(split[1]) workshopIds = append(workshopIds, workshopId) } return workshopIds } func DedicatedServerModsSetup(dstConfig dstConfig.DstConfig, modConfig string) error { if modConfig != "" { var serverModSetup []string workshopIds := WorkshopIds(modConfig) for _, workshopId := range workshopIds { serverModSetup = append(serverModSetup, "ServerModSetup(\""+workshopId+"\")") } modSetupPath := GetModSetup2(dstConfig) mods, err := fileUtils.ReadLnFile(modSetupPath) if err != nil { return err } var newServerModSetup []string for i := range serverModSetup { var notFind = true for j := range mods { if serverModSetup[i] == mods[j] { notFind = false break } } if notFind { newServerModSetup = append(newServerModSetup, serverModSetup[i]) } } newServerModSetup = append(newServerModSetup, mods...) err = fileUtils.WriterLnFile(modSetupPath, newServerModSetup) if err != nil { return err } } return nil } func GetModSetup2(dstConfig dstConfig.DstConfig) string { return filepath.Join(dstConfig.Force_install_dir, "mods", "dedicated_server_mods_setup.lua") } func ParseTemplate(templatePath string, data interface{}) string { // 读取文件内容 content, err := ioutil.ReadFile(templatePath) if err != nil { panic(err) } // 创建模板对象 tmpl, err := textTemplate.New("myTemplate").Parse(string(content)) if err != nil { panic(err) } // 执行模板并保存结果到字符串 buf := new(bytes.Buffer) err = tmpl.Execute(buf, data) if err != nil { panic(err) } return buf.String() } ================================================ FILE: internal/pkg/utils/envUtils.go ================================================ package utils import "runtime" func IsWindow() bool { os := runtime.GOOS return os == "windows" } ================================================ FILE: internal/pkg/utils/fileUtils/fileUtls.go ================================================ package fileUtils import ( "bufio" "dst-admin-go/internal/pkg/utils/systemUtils" "errors" "fmt" "io" "log" "os" "path/filepath" "sort" "strings" ) func Exists(path string) bool { _, err := os.Stat(path) if err != nil { return os.IsExist(err) } return true } func IsDir(path string) bool { s, err := os.Stat(path) if err != nil { return false } return s.IsDir() } func IsFile(path string) bool { return !IsDir(path) } func CreateDir(dirName string) bool { if dirName == "" { return false } if Exists(dirName) { return false } err := os.MkdirAll(dirName, 0755) if err != nil { log.Println(err) return false } return true } func CreateFile(fileName string) error { f, err := os.Create(fileName) if err != nil { return err } defer f.Close() return err } func WriterTXT(filename, content string) error { // 写入文件 // 判断文件是否存在 var file *os.File if _, err := os.Stat(filename); os.IsNotExist(err) { file, err = os.Create(filename) if err != nil { fmt.Println(err) } } else { //O_APPEND file, err = os.OpenFile(filename, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { return err } } defer file.Close() w := bufio.NewWriter(file) _, err2 := w.WriteString(content) if err2 != nil { return err2 } w.Flush() file.Sync() return nil } func ReadLnFile(filePath string) ([]string, error) { //打开文件 fi, err := os.Open(filePath) if err != nil { return nil, err } defer fi.Close() buf := bufio.NewScanner(fi) // 循环读取 var lineArr []string for { if !buf.Scan() { break //文件读完了,退出for } line := buf.Text() //获取每一行 lineArr = append(lineArr, line) } return lineArr, nil } func ReadFile(filePath string) (string, error) { data, err := os.ReadFile(filePath) if err != nil { fmt.Println("File reading error: ", err) return "", err } return string(data), err } func WriterLnFile(filename string, lines []string) error { var file *os.File if _, err := os.Stat(filename); os.IsNotExist(err) { file, err = os.Create(filename) if err != nil { fmt.Println(err) } } else { //O_APPEND file, err = os.OpenFile(filename, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { return err } } defer file.Close() w := bufio.NewWriter(file) for _, v := range lines { fmt.Fprintln(w, v) } return w.Flush() } func ReverseRead(filename string, lineNum uint) ([]string, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() //获取文件大小 fs, err := file.Stat() fileSize := fs.Size() var offset int64 = -1 //偏移量,初始化为-1,若为0则会读到EOF char := make([]byte, 1) //用于读取单个字节 lineStr := "" //存放一行的数据 buff := make([]string, 0, 100) for (-offset) <= fileSize { //通过Seek函数从末尾移动游标然后每次读取一个字节 file.Seek(offset, io.SeekEnd) _, err := file.Read(char) if err != nil { return buff, err } if char[0] == '\n' { // offset-- //windows跳过'\r' lineNum-- //到此读取完一行 buff = append(buff, lineStr) lineStr = "" if lineNum == 0 { return buff, nil } } else { lineStr = string(char) + lineStr } offset-- } buff = append(buff, lineStr) return buff, nil } func DeleteFile(path string) error { err := os.Remove(path) if err != nil { log.Printf("remove "+path+" : %v\n", err) return err } return nil } func DeleteDir(path string) error { home, err := systemUtils.Home() if err != nil { return err } if path == filepath.Join(home, ".klei/DoNotStarveTogether") { return errors.New(".klei/DoNotStarveTogether not allow to delete") } err = os.RemoveAll(path) if err != nil { log.Printf("remove err "+path+" : %v\n", err) } return err } func Rename(filePath, newName string) (err error) { err = os.Rename(filePath, newName) return } func FindWorldDirs(rootPath string) ([]string, error) { var dirs []string // 遍历目录并列出满足条件的目录 err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } // 如果是目录且名称包含 master 或 caves(不区分大小写) if info.IsDir() && (strings.Contains(strings.ToLower(info.Name()), "master") || strings.Contains(strings.ToLower(info.Name()), "caves")) { dirs = append(dirs, path) } return nil }) if err != nil { return nil, err } return dirs, nil } func ListDirectories(root string) ([]string, error) { var dirs []string err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { dirs = append(dirs, path) } return nil }) if err != nil { return nil, err } sort.Slice(dirs, func(i, j int) bool { fi, err := os.Stat(dirs[i]) if err != nil { return false } fj, err := os.Stat(dirs[j]) if err != nil { return false } return fi.ModTime().Before(fj.ModTime()) }) return dirs, nil } func CreateFileIfNotExists(path string) error { // 检查文件是否存在 _, err := os.Stat(path) if err == nil { // 文件已经存在,直接返回 return nil } if !os.IsNotExist(err) { // 其他错误,返回错误信息 return err } // 创建文件所在的目录 dir := filepath.Dir(path) err = os.MkdirAll(dir, 0755) if err != nil { // 创建目录失败,返回错误信息 return err } // 创建文件 _, err = os.Create(path) if err != nil { // 创建文件失败,返回错误信息 return err } // 创建成功,返回 nil return nil } func CreateDirIfNotExists(filepath string) { if !Exists(filepath) { CreateDir(filepath) } } func Copy(srcPath, outFileDir string) error { srcInfo, err := os.Stat(srcPath) if err != nil { return err } // 如果源文件是目录,则递归复制目录 if srcInfo.IsDir() { // 创建目标目录(如果不存在) err = os.MkdirAll(outFileDir, srcInfo.Mode()) if err != nil { return err } // 遍历源目录中的所有文件和子目录,并递归复制它们 srcDir, err := os.Open(srcPath) if err != nil { return err } defer srcDir.Close() files, err := srcDir.Readdir(-1) if err != nil { return err } for _, file := range files { srcFilePath := filepath.Join(srcPath, file.Name()) outFilePath := filepath.Join(outFileDir, filepath.Base(srcPath)) err = Copy(srcFilePath, outFilePath) if err != nil { return err } } return nil } return copyHelper(srcPath, outFileDir) } func copyHelper(srcPath, outFileDir string) error { // 打开源文件 srcFile, err := os.Open(srcPath) if err != nil { return err } defer srcFile.Close() // 创建目标目录(如果不存在) err = os.MkdirAll(outFileDir, 0755) if err != nil { return err } // 创建目标文件 outFilePath := filepath.Join(outFileDir, filepath.Base(srcPath)) outFile, err := os.Create(outFilePath) if err != nil { return err } defer outFile.Close() // 复制数据 _, err = io.Copy(outFile, srcFile) if err != nil { return err } return nil } ================================================ FILE: internal/pkg/utils/luaUtils/luaUtils.go ================================================ package luaUtils import ( "fmt" "log" "reflect" lua "github.com/yuin/gopher-lua" ) type Clock struct { TotalTimeInPhase int `lua:"totaltimeinphase"` Cycles int `lua:"cycles"` Phase string `lua:"phase"` RemainingTimeInPhase float64 `lua:"remainingtimeinphase"` MooomPhaseCycle int `lua:"mooomphasecycle"` Segs Segs `lua:"segs"` } type Segs struct { Night int `lua:"night"` Day int `lua:"day"` Dusk int `lua:"dusk"` } type IsRandom struct { Summer bool `lua:"summer"` Autumn bool `lua:"autumn"` Spring bool `lua:"spring"` Winter bool `lua:"winter"` } type Lengths struct { Summer int `lua:"summer"` Autumn int `lua:"autumn"` Spring int `lua:"spring"` Winter int `lua:"winter"` } type Seasons struct { Premode bool `lua:"premode"` Season string `lua:"season"` ElapsedDaysInSeason int `lua:"elapseddaysinseason"` IsRandom IsRandom `lua:"israndom"` Lengths Lengths `lua:"lengths"` RemainingDaysInSeason int `lua:"remainingdaysinseason"` Mode string `lua:"mode"` TotalDaysInSeason int `lua:"totaldaysinseason"` Segs map[string]interface{} `lua:"segs"` } type Data struct { Clock Clock `lua:"clock"` Seasons Seasons `lua:"seasons"` } func mapTableToStruct(table *lua.LTable, v reflect.Value) error { t := v.Type() for i := 0; i < t.NumField(); i++ { fieldType := t.Field(i) tag := fieldType.Tag.Get("lua") if tag == "" { continue } value := table.RawGetString(tag) if value == lua.LNil { continue } fieldValue := v.Field(i) switch fieldValue.Kind() { case reflect.Struct: if err := mapTableToStruct(value.(*lua.LTable), fieldValue); err != nil { return err } case reflect.Map: mapType := fieldValue.Type() keyType := mapType.Key() valueType := mapType.Elem() mapValue := reflect.MakeMap(mapType) tableValue, ok := value.(*lua.LTable) if !ok { return fmt.Errorf("expected lua.LTable, got %T", value) } tableValue.ForEach(func(key, value lua.LValue) { mapKey := reflect.New(keyType).Elem() err := luaValueToValue(key, mapKey) if err != nil { return } mapValue := reflect.New(valueType).Elem() err = luaValueToValue(value, mapValue) if err != nil { return } mapValue.Set(mapValue) }) fieldValue.Set(mapValue) default: if err := luaValueToValue(value, fieldValue); err != nil { return err } } } return nil } func luaValueToValue(lv lua.LValue, v reflect.Value) error { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if lv.Type() != lua.LTNumber { return fmt.Errorf("expected lua.LNumber, got %T", lv) } v.SetInt(int64(lv.(lua.LNumber))) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: if lv.Type() != lua.LTNumber { return fmt.Errorf("expected lua.LNumber, got %T", lv) } v.SetUint(uint64(lv.(lua.LNumber))) case reflect.Float32, reflect.Float64: if lv.Type() != lua.LTNumber { return fmt.Errorf("expected lua.LNumber, got %T", lv) } v.SetFloat(float64(lv.(lua.LNumber))) case reflect.Bool: if lv.Type() != lua.LTBool { return fmt.Errorf("expected lua.LBool, got %T", lv) } v.SetBool(bool(lv.(lua.LBool))) case reflect.String: if lv.Type() != lua.LTString { return fmt.Errorf("expected lua.LString, got %T", lv) } v.SetString(string(lv.(lua.LString))) case reflect.Map: if lv.Type() != lua.LTTable { return fmt.Errorf("expected lua.LTable, got %T", lv) } mapType := v.Type() keyType := mapType.Key() valueType := mapType.Elem() mapValue := reflect.MakeMap(mapType) table := lv.(*lua.LTable) table.ForEach(func(key, value lua.LValue) { mapKey := reflect.New(keyType).Elem() err := luaValueToValue(key, mapKey) if err != nil { return } mapValue := reflect.New(valueType).Elem() err = luaValueToValue(value, mapValue) if err != nil { return } mapValue.Set(mapValue) }) v.Set(mapValue) default: return fmt.Errorf("unsupported kind: %v", v.Kind()) } return nil } func mapTableToMap(table *lua.LTable, m map[string]interface{}) { table.ForEach(func(key, value lua.LValue) { keyStr := key.String() switch value.Type() { case lua.LTTable: nestedTable := value.(*lua.LTable) nestedMap := map[string]interface{}{} mapTableToMap(nestedTable, nestedMap) m[keyStr] = nestedMap case lua.LTNumber: m[keyStr] = float64(value.(lua.LNumber)) case lua.LTString: m[keyStr] = string(value.(lua.LString)) case lua.LTBool: m[keyStr] = bool(value.(lua.LBool)) default: m[keyStr] = nil } }) } func LuaTable2Map(script string) (map[string]interface{}, error) { L := lua.NewState() defer L.Close() err := L.DoString(script) if err != nil { return map[string]interface{}{}, err } table := L.Get(-1) L.Pop(1) data := map[string]interface{}{} mapTableToMap(table.(*lua.LTable), data) return data, nil } func LuaTable2Struct(script string, v reflect.Value) error { L := lua.NewState() defer L.Close() err := L.DoString(script) if err != nil { log.Println(err) return err } table := L.Get(-1) L.Pop(1) err = mapTableToStruct(table.(*lua.LTable), v) if err != nil { log.Println(err) return err } return nil } ================================================ FILE: internal/pkg/utils/shellUtils/shellUitls.go ================================================ package shellUtils import ( "bytes" "fmt" "os" "os/exec" "golang.org/x/text/encoding/simplifiedchinese" ) func ExecuteCommandInWin(command string) (string, error) { cmd := exec.Command("cmd", "/C", command) output, err := cmd.Output() if err != nil { return "", err } return string(output), nil } // ExecuteCommand 执行给定的 Shell 命令,并返回输出和错误(如果有的话)。 func ExecuteCommand(command string) (string, error) { cmd := exec.Command("sh", "-c", command) var out bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr err := cmd.Run() if err != nil { return "", fmt.Errorf("run command error: %v, ERROR: %s", err, stderr.String()) } if stderr.String() != "" { return "", fmt.Errorf("exec command error: %s", stderr.String()) } return out.String(), nil } // 执行shell命令 func Shell(cmd string) (res string, err error) { //var execCmd *exec.Cmd //if runtime.GOOS == "windows" { // execCmd = exec.Command("cmd.exe", "/c", cmd) //} else { // execCmd = exec.Command("bash", "-c", cmd) //} //var ( // stdout bytes.Buffer // stderr bytes.Buffer //) // //execCmd.Stdout = &stdout //execCmd.Stderr = &stderr //err = execCmd.Run() //if err != nil { // log.Println("error: " + err.Error()) //} // //output := ConvertByte2String(stderr.Bytes(), GB18030) //errput := ConvertByte2String(stdout.Bytes(), GB18030) ////res = fmt.Sprintf("Output:\n%s\nError:\n%s", stdout.String(), stderr.String()) // //// log.Printf("shell exec: %s \nOutput:\n%s\nError:\n%s", cmd, output, errput) //if errput != "" { // log.Printf("shell exec: %s Error:\n%s", cmd, errput) //} //if output != "" { // log.Printf("shell exec: %s nOutput:\n%s", cmd, output) //} // //return stdout.String(), err return ExecuteCommand(cmd) } type Charset string const ( UTF8 = Charset("UTF-8") GB18030 = Charset("GB18030") ) func ConvertByte2String(byte []byte, charset Charset) string { var str string switch charset { case GB18030: decodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(byte) str = string(decodeBytes) case UTF8: fallthrough default: str = string(byte) } return str } func Chmod(filePath string) error { // 获取文件的当前权限 fileInfo, err := os.Stat(filePath) if err != nil { return err } // 添加可执行权限 newMode := fileInfo.Mode() | 0100 // 更改文件权限 err = os.Chmod(filePath, newMode) if err != nil { return err } return nil } ================================================ FILE: internal/pkg/utils/systemUtils/SystemUtils.go ================================================ package systemUtils import ( "bytes" "errors" "fmt" "io/ioutil" "net/http" "os" "os/exec" "os/user" "runtime" "strings" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/host" "github.com/shirou/gopsutil/mem" ) // Home returns the home directory for the executing user. // // This uses an OS-specific method for discovering the home directory. // An error is returned if a home directory cannot be detected. func Home() (string, error) { user, err := user.Current() if nil == err { return user.HomeDir, nil } // cross compile support if runtime.GOOS == "windows" { return homeWindows() } // Unix-like system, so just assume Unix return homeUnix() } func HomePath() string { home, err := Home() if err != nil { panic("Home path error: " + err.Error()) } return home } func homeUnix() (string, error) { // First prefer the HOME environmental variable if home := os.Getenv("HOME"); home != "" { return home, nil } // If that fails, try the shell var stdout bytes.Buffer cmd := exec.Command("sh", "-c", "eval echo ~$USER") cmd.Stdout = &stdout if err := cmd.Run(); err != nil { return "", err } result := strings.TrimSpace(stdout.String()) if result == "" { return "", errors.New("blank output when reading home directory") } return result, nil } func homeWindows() (string, error) { drive := os.Getenv("HOMEDRIVE") path := os.Getenv("HOMEPATH") home := drive + path if drive == "" || path == "" { home = os.Getenv("USERPROFILE") } if home == "" { return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank") } return home, nil } type HostInfo struct { Os string `json:"os"` HostName string `json:"hostname"` Platform string `json:"platform"` KernelArch string `json:"kernelArch"` } type MemInfo struct { Total uint64 `json:"total"` Available uint64 `json:"available"` Used uint64 `json:"used"` UsedPercent float64 `json:"usedPercent"` } type CpuInfo struct { Cores int `json:"cores"` CpuPercent []float64 `json:"cpuPercent"` CpuUsedPercent float64 `json:"cpuUsedPercent"` CpuUsed float64 `json:"cpuUsed"` } type DiskInfo struct { Devices []deviceInfo `json:"devices"` } type deviceInfo struct { Device string `json:"device"` Mountpoint string `json:"mountpoint"` Fstype string `json:"fstype"` Opts string `json:"opts"` Total uint64 `json:"total"` Usage float64 `json:"usage"` InodesUsage float64 `json:"inodesUsage"` } func GetDiskInfo() *DiskInfo { //info, _ := disk.IOCounters() //所有硬盘的io信息 diskPart, err := disk.Partitions(false) if err != nil { fmt.Println(err) } // fmt.Println(diskPart) var devices []deviceInfo for _, dp := range diskPart { device := deviceInfo{ Device: dp.Device, Mountpoint: dp.Mountpoint, Fstype: dp.Fstype, Opts: dp.Opts, } diskUsed, _ := disk.Usage(dp.Mountpoint) // fmt.Printf("分区总大小: %d MB \n", diskUsed.Total/1024/1024) // fmt.Printf("分区使用率: %.3f %% \n", diskUsed.UsedPercent) // fmt.Printf("分区inode使用率: %.3f %% \n", diskUsed.InodesUsedPercent) device.Total = diskUsed.Total / 1024 / 1024 device.Usage = diskUsed.UsedPercent device.InodesUsage = diskUsed.InodesUsedPercent devices = append(devices, device) } return &DiskInfo{ Devices: devices, } } func GetCpuInfo() *CpuInfo { cpuInfo := &CpuInfo{} cpuPercent, _ := cpu.Percent(0, false) cpuInfo.Cores, _ = cpu.Counts(true) if len(cpuPercent) == 1 { cpuInfo.CpuUsedPercent = cpuPercent[0] cpuInfo.CpuUsed = cpuInfo.CpuUsedPercent * 0.01 * float64(cpuInfo.Cores) } cpuInfo.CpuPercent, _ = cpu.Percent(0, true) return cpuInfo } func GetHostInfo() *HostInfo { info, _ := host.Info() return &HostInfo{ Os: info.OS, HostName: info.Hostname, Platform: info.Platform, KernelArch: info.KernelArch, } } func GetMemInfo() *MemInfo { v, _ := mem.VirtualMemory() // almost every return value is a struct //fmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent) // convert to JSON. String() is also implemented //fmt.Println(v) return &MemInfo{ Total: v.Total, Available: v.Available, Used: v.Used, UsedPercent: v.UsedPercent, } } func GetPublicIP() (string, error) { resp, err := http.Get("https://api.ipify.org/") if err != nil { return "", err } defer resp.Body.Close() ip, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(ip), nil } ================================================ FILE: internal/pkg/utils/zip/zip.go ================================================ package zip import ( "archive/zip" "errors" "io" "log" "os" "path/filepath" "strings" ) func zipDir(dirPath string, zipWriter *zip.Writer, basePath string) error { fileInfos, err := os.ReadDir(dirPath) if err != nil { return err } for _, fileInfo := range fileInfos { path := filepath.Join(dirPath, fileInfo.Name()) if fileInfo.IsDir() { err := zipDir(path, zipWriter, basePath) if err != nil { return err } } else { file, err := os.Open(path) if err != nil { return err } defer file.Close() relPath, err := filepath.Rel(basePath, path) if err != nil { return err } zipEntry, err := zipWriter.Create(filepath.ToSlash(relPath)) if err != nil { return err } _, err = io.Copy(zipEntry, file) if err != nil { return err } } } return nil } func Zip(sourceDir, targetZip string) error { zipFile, err := os.Create(targetZip) if err != nil { return err } defer zipFile.Close() zipWriter := zip.NewWriter(zipFile) defer zipWriter.Close() basePath := filepath.Dir(sourceDir) err = zipDir(sourceDir, zipWriter, basePath) if err != nil { return err } return nil } func Unzip(zipFile, destDir string) error { reader, err := zip.OpenReader(zipFile) if err != nil { return err } defer reader.Close() for _, file := range reader.File { path := filepath.Join(destDir, file.Name) if file.FileInfo().IsDir() { err = os.MkdirAll(path, os.ModePerm) if err != nil { return err } continue } err = os.MkdirAll(filepath.Dir(path), os.ModePerm) if err != nil { return err } zipEntry, err := file.Open() if err != nil { return err } defer zipEntry.Close() targetFile, err := os.Create(path) if err != nil { return err } defer targetFile.Close() _, err = io.Copy(targetFile, zipEntry) if err != nil { return err } } return nil } func Unzip3(source, destination string) error { reader, err := zip.OpenReader(source) if err != nil { return err } defer reader.Close() var clusterIniPath string for _, file := range reader.File { if strings.HasSuffix(file.Name, "cluster.ini") { clusterIniPath = file.Name break } } if clusterIniPath == "" { return errors.New("压缩包中缺少 cluster.ini 文件") } clusterPath := filepath.Dir(clusterIniPath) clusterPath = strings.TrimSuffix(clusterPath, "/") clusterPath = strings.TrimSuffix(clusterPath, "\\") log.Println("clusterPath", clusterPath) for _, file := range reader.File { // 获取相对路径 relativePath := strings.TrimPrefix(file.Name, clusterPath) relativePath = strings.TrimPrefix(relativePath, "/") relativePath = strings.TrimPrefix(relativePath, "\\") extractedFilePath := filepath.Join(destination, relativePath) log.Println("extractedFilePath", extractedFilePath) if file.FileInfo().IsDir() { os.MkdirAll(extractedFilePath, os.ModePerm) continue } if err := os.MkdirAll(filepath.Dir(extractedFilePath), os.ModePerm); err != nil { return err } writer, err := os.Create(extractedFilePath) if err != nil { return err } defer writer.Close() reader, err := file.Open() if err != nil { return err } defer reader.Close() if _, err := io.Copy(writer, reader); err != nil { return err } } return nil } //func Unzip3(source, destination string) error { // reader, err := zip.OpenReader(source) // if err != nil { // return err // } // defer reader.Close() // // for _, file := range reader.File { // filePath := filepath.Join(destination, file.Name) // if file.FileInfo().IsDir() { // os.MkdirAll(filePath, os.ModePerm) // continue // } // // if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { // return err // } // // writer, err := os.Create(filePath) // if err != nil { // return err // } // defer writer.Close() // // reader, err := file.Open() // if err != nil { // return err // } // defer reader.Close() // // if _, err := io.Copy(writer, reader); err != nil { // return err // } // } // // return nil //} func Unzip2(zipFile, destDir, newName string) error { r, err := zip.OpenReader(zipFile) if err != nil { log.Println(err) return err } defer r.Close() for _, f := range r.File { if f.Name == "" { continue } parts := strings.Split(f.Name, string(filepath.Separator)) // 使用路径分隔符拆分路径 extractedFilePath := "" if newName == parts[0] { parts = parts[1:] // 去掉第一个部分,即一级目录 newPath := filepath.Join(parts...) // 组合新的路径 // 构建解压后的文件路径 extractedFilePath = filepath.Join(destDir, newName, newPath) } else { extractedFilePath = filepath.Join(destDir, newName, f.Name) } log.Println(">>> ", f.Name, extractedFilePath) if f.FileInfo().IsDir() { // 创建目录 os.MkdirAll(extractedFilePath, os.ModePerm) continue } // 创建解压后的文件 if err := os.MkdirAll(filepath.Dir(extractedFilePath), os.ModePerm); err != nil { return err } outFile, err := os.OpenFile(extractedFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { log.Println(err) return err } defer outFile.Close() // 打开压缩文件中的文件 rc, err := f.Open() if err != nil { log.Println(err) return err } defer rc.Close() // 将压缩文件中的内容复制到解压文件中 _, err = io.Copy(outFile, rc) if err != nil { log.Println(err) return err } } return nil } ================================================ FILE: internal/service/archive/path_resolver.go ================================================ package archive import ( "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/dstConfig" "io" "log" "net/http" "os" "path/filepath" "runtime" "strconv" "strings" ) type PathResolver struct { homePath string dstConfig dstConfig.Config } func NewPathResolver(dstConfig dstConfig.Config) (*PathResolver, error) { home, err := os.UserHomeDir() if err != nil { return nil, err } return &PathResolver{ homePath: home, dstConfig: dstConfig, }, nil } func (r *PathResolver) KleiBasePath(clusterName string) string { config, err := r.dstConfig.GetDstConfig(clusterName) if err != nil { log.Panic(err) } persistentStorageRoot := config.Persistent_storage_root confDir := config.Conf_dir if persistentStorageRoot != "" { if confDir == "" { confDir = "DoNotStarveTogether" } kleiDstPath := filepath.Join(persistentStorageRoot, confDir) return kleiDstPath } if runtime.GOOS == "windows" { return filepath.Join( r.homePath, "Documents", "klei", "DoNotStarveTogether", ) } return filepath.Join( r.homePath, ".klei", "DoNotStarveTogether", ) } func (r *PathResolver) ClusterPath(cluster string) string { return filepath.Join( r.KleiBasePath(cluster), cluster, ) } func (r *PathResolver) LevelPath(cluster, level string) string { return filepath.Join( r.ClusterPath(cluster), level, ) } func (r *PathResolver) DataFilePath( cluster, level, fileName string, ) string { return filepath.Join( r.LevelPath(cluster, level), fileName, ) } func (r *PathResolver) ClusterIniPath(clusterName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, "cluster.ini") } func (r *PathResolver) ClusterTokenPath(clusterName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, "cluster_token.txt") } func (r *PathResolver) AdminlistPath(clusterName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, "adminlist.txt") } func (r *PathResolver) BlocklistPath(clusterName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, "blocklist.txt") } func (r *PathResolver) BlacklistPath(clusterName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, "blocklist.txt") } func (r *PathResolver) WhitelistPath(clusterName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, "whitelist.txt") } func (r *PathResolver) ModoverridesPath(clusterName, levelName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, levelName, "modoverrides.lua") } func (r *PathResolver) LeveldataoverridePath(clusterName, levelName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, levelName, "leveldataoverride.lua") } func (r *PathResolver) ServerIniPath(clusterName string, levelName string) string { return filepath.Join(r.KleiBasePath(clusterName), clusterName, levelName, "server.ini") } func (r *PathResolver) ServerLogPath(cluster string, levelName string) string { return filepath.Join(r.LevelPath(cluster, levelName), "server_log.txt") } func (r *PathResolver) GetUgcWorkshopModPath(clusterName, levelName, workshopId string) string { // dstConfig := dstConfigUtils.GetDstConfig() config, _ := r.dstConfig.GetDstConfig(clusterName) workshopModPath := "" if config.Ugc_directory != "" { workshopModPath = filepath.Join(r.GetUgcModPath(clusterName), "content", "322330", workshopId) } else { workshopModPath = filepath.Join(config.Force_install_dir, "ugc_mods", clusterName, levelName, "content", "322330", workshopId) } return workshopModPath } func (r *PathResolver) GetUgcModPath(clusterName string) string { config, _ := r.dstConfig.GetDstConfig(clusterName) ugcModPath := "" if config.Ugc_directory != "" { ugcModPath = config.Ugc_directory } else { ugcModPath = filepath.Join(config.Force_install_dir, "ugc_mods") } return ugcModPath } func (r *PathResolver) GetUgcAcfPath(clusterName, levelName string) string { ugcModPath := r.GetUgcModPath(clusterName) config, _ := r.dstConfig.GetDstConfig(clusterName) p := "" if config.Ugc_directory == "" { p = filepath.Join(ugcModPath, clusterName, levelName, "appworkshop_322330.acf") } else { p = filepath.Join(ugcModPath, "appworkshop_322330.acf") } return p } func (r *PathResolver) GetModSetup(clusterName string) string { cluster, _ := r.dstConfig.GetDstConfig(clusterName) dstServerPath := cluster.Force_install_dir if r.IsBeta(clusterName) { dstServerPath = dstServerPath + "-beta" } return filepath.Join(dstServerPath, "mods", "dedicated_server_mods_setup.lua") } func (r *PathResolver) IsBeta(clusterName string) bool { config, err := r.dstConfig.GetDstConfig(clusterName) if err != nil { return false } return config.Beta == 1 } func (r *PathResolver) GetLocalDstVersion(clusterName string) (int64, error) { dstConfig, err := r.dstConfig.GetDstConfig(clusterName) if err != nil { return 0, err } dstInstallDir := dstConfig.Force_install_dir if dstConfig.Beta == 1 { dstInstallDir = dstInstallDir + "-beta" } versionTextPath := filepath.Join(dstInstallDir, "version.txt") return r.dstVersion(versionTextPath) } func (r *PathResolver) GetLastDstVersion() (int64, error) { url := "http://ver.tugos.cn/getLocalVersion" resp, err := http.Get(url) if err != nil { log.Println(err) } body, err := io.ReadAll(resp.Body) if err != nil { log.Println(err) } s := string(body) veriosn, err := strconv.Atoi(s) if err != nil { veriosn = 0 } return int64(veriosn), nil } func (r *PathResolver) dstVersion(versionTextPath string) (int64, error) { // 使用filepath.Clean确保路径格式正确 cleanPath := filepath.Clean(versionTextPath) // 使用filepath.Abs获取绝对路径 absPath, err := filepath.Abs(cleanPath) if err != nil { log.Println("Error getting absolute path:", err) return 0, err } // 打印绝对路径 log.Println("Absolute Path:", absPath) version, err := fileUtils.ReadFile(versionTextPath) if err != nil { log.Println(err) return 0, err } version = strings.Replace(version, "\r", "", -1) version = strings.Replace(version, "\n", "", -1) l, err := strconv.ParseInt(version, 10, 64) if err != nil { log.Println(err) return 0, err } return l, nil } ================================================ FILE: internal/service/backup/backup_service.go ================================================ package backup import ( "dst-admin-go/internal/database" "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/context" "dst-admin-go/internal/pkg/utils/dstUtils" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/pkg/utils/shellUtils" "dst-admin-go/internal/pkg/utils/zip" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/dstConfig" "dst-admin-go/internal/service/game" "io/ioutil" "log" "os" "path/filepath" "strings" "time" "github.com/gin-gonic/gin" ) type BackupService struct { archive *archive.PathResolver dstConfig dstConfig.Config gameProcess game.Process } type BackupInfo struct { FileName string `json:"fileName"` FileSize int64 `json:"fileSize"` CreateTime time.Time `json:"createTime"` Time int64 `json:"time"` } type BackupSnapshot struct { Enable int `json:"enable"` Interval int `json:"interval"` MaxSnapshots int `json:"maxSnapshots"` IsCSave int `json:"isCSave"` } func NewBackupService(archive *archive.PathResolver, dstConfig dstConfig.Config, gameProcess game.Process) *BackupService { return &BackupService{ archive: archive, dstConfig: dstConfig, gameProcess: gameProcess, } } func (b *BackupService) GetBackupList(clusterName string) []BackupInfo { config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return []BackupInfo{} } backupPath := config.Backup var backupList []BackupInfo if !fileUtils.Exists(backupPath) { return backupList } //获取文件或目录相关信息 fileInfoList, err := ioutil.ReadDir(backupPath) if err != nil { log.Panicln(err) } for _, file := range fileInfoList { if file.IsDir() { continue } suffix := filepath.Ext(file.Name()) if suffix == ".zip" || suffix == ".tar" { backup := BackupInfo{ FileName: file.Name(), FileSize: file.Size(), CreateTime: file.ModTime(), Time: file.ModTime().Unix(), } backupList = append(backupList, backup) } } return backupList } func (b *BackupService) RenameBackup(ctx *gin.Context, fileName, newName string) { clusterName := context.GetClusterName(ctx) config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return } backupPath := config.Backup err = fileUtils.Rename(filepath.Join(backupPath, fileName), filepath.Join(backupPath, newName)) if err != nil { return } } func (b *BackupService) DeleteBackup(ctx *gin.Context, fileNames []string) { clusterName := context.GetClusterName(ctx) config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return } backupPath := config.Backup for _, fileName := range fileNames { filePath := filepath.Join(backupPath, fileName) if !fileUtils.Exists(filePath) { continue } err := fileUtils.DeleteFile(filePath) if err != nil { return } } } func (b *BackupService) RestoreBackup(ctx *gin.Context, backupName string) { clusterName := context.GetClusterName(ctx) config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return } filePath := filepath.Join(config.Backup, backupName) clusterPath := filepath.Join(b.archive.ClusterPath(clusterName)) err = fileUtils.DeleteDir(clusterPath) if err != nil { log.Panicln("删除失败,", clusterPath, err) } log.Println("正在恢复存档", filePath, filepath.Join(b.archive.KleiBasePath(clusterName))) // err = zip.Unzip2(filePath, filepath.Join(constant.HOME_PATH, ".klei/DoNotStarveTogether"), cluster.ClusterName) err = zip.Unzip3(filePath, clusterPath) if err != nil { log.Panicln("解压失败,", filePath, clusterPath, err) } // 安装mod modoverride, err := fileUtils.ReadFile(b.archive.ModoverridesPath(clusterName, "Master")) if err != nil { log.Println("读取模组失败", err) } config, err = b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println(err.Error()) } err = dstUtils.DedicatedServerModsSetup(config, modoverride) if err != nil { log.Println(err.Error()) } } func (b *BackupService) CreateBackup(clusterName, backupName string) { config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return } backupPath := config.Backup // 执行 CSave 命令 err = b.gameProcess.Command(clusterName, "Master", "c_save()") if err != nil { log.Println("CSave command error:", err) } // 等待保存完成 time.Sleep(2 * time.Second) src := b.archive.ClusterPath(clusterName) if !fileUtils.Exists(backupPath) { log.Panicln("backup path is not exists") } if backupName == "" { backupName = b.GenGameBackUpName(clusterName) } dst := filepath.Join(backupPath, backupName) log.Println("src", src, dst) err = zip.Zip(src, dst) if err != nil { log.Panicln("create backup error", err) } log.Println("创建备份成功") } func (b *BackupService) DownloadBackup(c *gin.Context) { fileName := c.Query("fileName") clusterName := c.GetHeader("level") config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return } filePath := filepath.Join(config.Backup, fileName) //打开文件 _, err = os.Open(filePath) //非空处理 if err != nil { log.Panicln("download filePath error", err) } c.Header("Content-Type", "application/octet-stream") c.Header("Content-Disposition", "attachment; filename="+fileName) c.Header("Content-Transfer-Encoding", "binary") // c.Header("Content-Length", strconv.FormatInt(f.Size(), 10)) c.File(filePath) } func (b *BackupService) UploadBackup(c *gin.Context) { // 单文件 file, _ := c.FormFile("file") log.Println(file.Filename) clusterName := context.GetClusterName(c) config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return } dst := filepath.Join(config.Backup, file.Filename) if fileUtils.Exists(dst) { log.Panicln("backup is existed") } // 上传文件至指定的完整文件路径 err = c.SaveUploadedFile(file, dst) if err != nil { return } // c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) } func (b *BackupService) ScheduleBackupSnapshots() { log.Println("开始创建快照") for { db := database.Db snapshot := model.BackupSnapshot{} db.First(&snapshot) if snapshot.Enable == 1 { if snapshot.Interval == 0 { snapshot.Interval = 8 } if snapshot.MaxSnapshots == 0 { snapshot.MaxSnapshots = 6 } time.Sleep(time.Duration(snapshot.Interval) * time.Minute) // 定时创建备份,每隔 x 分钟备份一次 // Get the first available cluster config (or "MyCluster" as default) clusterName := "MyCluster" config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config for snapshot:", err) continue } if config.Cluster != "" { snapshotPrefix := "(snapshot)" if snapshot.IsCSave == 1 { // 执行 CSave 命令 err := b.gameProcess.Command(config.Cluster, "Master", "c_save()") if err != nil { log.Println("CSave command error:", err) } // 等待保存完成 time.Sleep(2 * time.Second) } b.CreateSnapshotBackup(snapshotPrefix, config.Cluster) // 删除快照 b.DeleteBackupSnapshots(snapshotPrefix, snapshot.MaxSnapshots, config.Cluster, config.Backup) } } else { time.Sleep(1 * time.Minute) } } } func sumMd5(filePath string) string { // find save -type f -exec md5sum {} \; | awk '{print $1}' | sort | md5sum comamd := "find " + filePath + " -type f -exec md5sum {} \\; | awk '{print $1}' | sort | md5sum" info, err := shellUtils.ExecuteCommand(comamd) if err != nil { return "" } return info } func (b *BackupService) CreateSnapshotBackup(prefix, clusterName string) { config, err := b.dstConfig.GetDstConfig(clusterName) if err != nil { log.Println("failed to get dst config:", err) return } snapshotMd5FilePath := "./snapshotMd5" fileUtils.CreateFileIfNotExists(snapshotMd5FilePath) src := b.archive.ClusterPath(clusterName) dst := filepath.Join(config.Backup, b.GenBackUpSnapshotName(prefix, clusterName)) log.Println("[Snapshot]正在定时创建游戏备份", "src: ", src, "dst: ", dst) err = zip.Zip(src, dst) if err != nil { log.Println("[Snapshot]create backup error", err) } } func (b *BackupService) DeleteBackupSnapshots(prefix string, maxSnapshots int, clusterName, backupPath string) { log.Println("[Snapshot]正在删除快照备份", "maxSnapshots", maxSnapshots, "clusterName: ", clusterName) backupList := b.GetBackupList(clusterName) var newBackupList []BackupInfo for i := range backupList { name := backupList[i].FileName if strings.HasPrefix(name, prefix) { newBackupList = append(newBackupList, backupList[i]) } } if len(newBackupList) > maxSnapshots { deleteBackupList := newBackupList[:len(newBackupList)-maxSnapshots] for i := range deleteBackupList { filePath := filepath.Join(backupPath, deleteBackupList[i].FileName) log.Println("删除快照备份", filePath) if !fileUtils.Exists(filePath) { continue } err := fileUtils.DeleteFile(filePath) if err != nil { return } } } } func (b *BackupService) backupPath() string { // dstConfig := dstConfigUtils.GetDstConfig() // backupPath := dstConfig.Backup // if !fileUtils.Exists(backupPath) { // log.Panicln("backup path is not exists") // } // return backupPath return "" } var SeasonMap = map[string]string{ "spring": "春天", "summer": "夏天", "autumn": "秋天", "winter": "冬天", } // GenGameBackUpName 备份名称增加存档信息如 猜猜我是谁的世界-10天-spring-1-20-2023071415 func (b *BackupService) GenGameBackUpName(clusterName string) string { // 简化实现,使用时间戳和集群名称 backupName := time.Now().Format("2006年01月02日15点04分05秒") + "_" + clusterName + ".zip" return backupName } func (b *BackupService) GenBackUpSnapshotName(prefix, clusterName string) string { backupName := b.GenGameBackUpName(clusterName) backupName = prefix + backupName return backupName } ================================================ FILE: internal/service/dstConfig/dst_config.go ================================================ package dstConfig type DstConfig struct { Steamcmd string `json:"steamcmd"` Force_install_dir string `json:"force_install_dir"` DoNotStarveServerDirectory string `json:"donot_starve_server_directory"` Cluster string `json:"cluster"` Backup string `json:"backup"` Mod_download_path string `json:"mod_download_path"` Bin int `json:"bin"` Beta int `json:"beta"` Ugc_directory string `json:"ugc_directory"` // 根目录位置 Persistent_storage_root string `json:"persistent_storage_root"` // 存档相对位置 Conf_dir string `json:"conf_dir"` } type Config interface { GetDstConfig(clusterName string) (DstConfig, error) SaveDstConfig(clusterName string, config DstConfig) error } ================================================ FILE: internal/service/dstConfig/factory.go ================================================ package dstConfig import ( "gorm.io/gorm" ) func NewDstConfig(db *gorm.DB) Config { dstConfig := NewOneDstConfig(db) return &dstConfig } ================================================ FILE: internal/service/dstConfig/one_dst_config.go ================================================ package dstConfig import ( "dst-admin-go/internal/pkg/utils/fileUtils" "os" "path/filepath" "runtime" "strconv" "strings" "gorm.io/gorm" ) const dst_config_path = "./dst_config" type OneDstConfig struct { db *gorm.DB } func NewOneDstConfig(db *gorm.DB) OneDstConfig { return OneDstConfig{ db: db, } } func (o *OneDstConfig) kleiBasePath(config DstConfig) string { home, _ := os.UserHomeDir() persistentStorageRoot := config.Persistent_storage_root confDir := config.Conf_dir if persistentStorageRoot != "" { if confDir == "" { confDir = "DoNotStarveTogether" } kleiDstPath := filepath.Join(persistentStorageRoot, confDir) return kleiDstPath } if runtime.GOOS == "windows" { return filepath.Join( home, "Documents", "klei", "DoNotStarveTogether", ) } return filepath.Join( home, ".klei", "DoNotStarveTogether", ) } func (o *OneDstConfig) GetDstConfig(clusterName string) (DstConfig, error) { dstConfig := DstConfig{} //判断是否存在,不存在创建一个 if !fileUtils.Exists(dst_config_path) { if err := fileUtils.CreateFile(dst_config_path); err != nil { return dstConfig, err } } data, err := fileUtils.ReadLnFile(dst_config_path) if err != nil { return dstConfig, err } for _, value := range data { if value == "" { continue } // TODO 这里解析有问题,如果路径含有 steamcmd 就会存在问题 if strings.Contains(value, "steamcmd=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Steamcmd = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "force_install_dir=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Force_install_dir = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "donot_starve_server_directory=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.DoNotStarveServerDirectory = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "persistent_storage_root=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Persistent_storage_root = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "cluster=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Cluster = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "backup=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Backup = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "mod_download_path=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Mod_download_path = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "bin=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) bin, _ := strconv.ParseInt(strings.Replace(s, "\\n", "", -1), 10, 64) dstConfig.Bin = int(bin) } } if strings.Contains(value, "beta=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) beta, _ := strconv.ParseInt(strings.Replace(s, "\\n", "", -1), 10, 64) dstConfig.Beta = int(beta) } } if strings.Contains(value, "ugc_directory=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Ugc_directory = strings.Replace(s, "\\n", "", -1) } } if strings.Contains(value, "conf_dir=") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) dstConfig.Conf_dir = strings.Replace(s, "\\n", "", -1) } } } // 设置默认值 if dstConfig.Cluster == "" { dstConfig.Cluster = "Cluster1" } if dstConfig.Backup == "" { defaultPath := filepath.Join(o.kleiBasePath(dstConfig), "backup") fileUtils.CreateDirIfNotExists(defaultPath) dstConfig.Backup = defaultPath } if dstConfig.Mod_download_path == "" { defaultPath := filepath.Join(o.kleiBasePath(dstConfig), "mod_config_download") fileUtils.CreateDirIfNotExists(defaultPath) dstConfig.Mod_download_path = defaultPath } if dstConfig.Bin == 0 { dstConfig.Bin = 32 } return dstConfig, nil } func (o *OneDstConfig) SaveDstConfig(clusterName string, dstConfig DstConfig) error { oldDstConfig, err := o.GetDstConfig(clusterName) if err != nil { return err } if dstConfig.Steamcmd == "" { dstConfig.Steamcmd = oldDstConfig.Steamcmd } if dstConfig.Force_install_dir == "" { dstConfig.Force_install_dir = oldDstConfig.Force_install_dir } if dstConfig.Cluster == "" { dstConfig.Cluster = oldDstConfig.Cluster } if dstConfig.Backup == "" { dstConfig.Backup = oldDstConfig.Backup } if dstConfig.Mod_download_path == "" { dstConfig.Mod_download_path = oldDstConfig.Mod_download_path } err = fileUtils.WriterLnFile(dst_config_path, []string{ "steamcmd=" + dstConfig.Steamcmd, "force_install_dir=" + dstConfig.Force_install_dir, "donot_starve_server_directory=" + dstConfig.DoNotStarveServerDirectory, "ugc_directory=" + dstConfig.Ugc_directory, "conf_dir=" + dstConfig.Conf_dir, "persistent_storage_root=" + dstConfig.Persistent_storage_root, "cluster=" + dstConfig.Cluster, "backup=" + dstConfig.Backup, "mod_download_path=" + dstConfig.Mod_download_path, "bin=" + strconv.Itoa(dstConfig.Bin), "beta=" + strconv.Itoa(dstConfig.Beta), }) return err } ================================================ FILE: internal/service/dstMap/dst_map.go ================================================ package dstMap import ( "encoding/base64" "fmt" "image" "image/color" "image/png" "io/ioutil" "os" "regexp" ) // Color 定义一个RGB颜色 type Color struct { R, G, B uint8 Name string } // DSTMapGenerator 存储地图生成器的状态 type DSTMapGenerator struct { tileColors map[int]Color entityColors map[string]color.Color } // NewDSTMapGenerator 创建新的地图生成器实例 func NewDSTMapGenerator() *DSTMapGenerator { g := &DSTMapGenerator{ tileColors: make(map[int]Color), entityColors: make(map[string]color.Color), } // 初始化tile颜色映射 g.tileColors = map[int]Color{ 0: {42, 42, 42, "地表虚空"}, 1: {42, 42, 44, "一个虚空"}, 2: {80, 76, 65, "卵石路"}, 3: {90, 105, 104, "矿石区"}, 4: {117, 107, 85, "无地皮"}, 5: {144, 125, 89, "热带草原地皮"}, 6: {48, 67, 39, "长草地皮"}, 7: {40, 47, 18, "森林地皮"}, 8: {81, 28, 194, "沼泽地皮"}, 9: {0, 0, 7, "空"}, 10: {85, 69, 48, "木地板"}, 11: {64, 75, 116, "地毯地板"}, 12: {115, 133, 201, "棋盘地板"}, 13: {139, 131, 115, "鸟粪地皮"}, 14: {74, 65, 77, "蓝真菌"}, 15: {67, 70, 32, "黏滑地皮"}, 16: {75, 75, 73, "洞穴岩石地皮"}, 17: {66, 49, 30, "泥泞地皮"}, 18: {115, 113, 107, "远古地皮"}, 19: {86, 86, 81, "仿远古地皮"}, 20: {74, 61, 84, "远古瓷砖"}, 21: {66, 50, 76, "仿远古瓷砖"}, 22: {39, 38, 39, "远古雕砖"}, 23: {34, 35, 34, "仿远古雕砖"}, 24: {70, 44, 43, "红真菌"}, 25: {62, 76, 61, "绿真菌"}, 26: {42, 42, 44, "空"}, 27: {42, 42, 44, "空"}, 28: {42, 42, 44, "空"}, 29: {42, 42, 44, "空"}, 30: {91, 62, 14, "落叶林地皮"}, 31: {117, 86, 46, "沙漠地皮"}, 32: {31, 27, 27, "龙鳞地皮"}, 33: {128, 128, 128, "崩溃"}, 34: {128, 128, 128, "崩溃"}, 35: {47, 44, 47, "暴食沼泽"}, 36: {158, 104, 105, "粉桦树林【暴食】"}, 37: {137, 113, 113, "粉【暴食】"}, 38: {81, 97, 100, "蓝长草【暴食】"}, 39: {66, 58, 49, "耕地地皮"}, 40: {42, 42, 44, "空"}, 41: {119, 113, 97, "白【暴食】"}, 42: {84, 108, 107, "岩石海滩"}, 43: {67, 133, 142, "月球环形山"}, 44: {154, 146, 186, "贝壳海滩"}, 45: {138, 96, 73, "远古石刻"}, 46: {66, 86, 82, "变异真菌地皮"}, 47: {61, 57, 46, "耕地地皮"}, 48: {42, 42, 44, "空"}, 200: {0, 0, 11, "深渊"}, 201: {18, 66, 73, "浅海"}, 202: {18, 66, 73, "浅海海岸"}, 203: {7, 46, 61, "中海"}, 204: {1, 32, 46, "深海"}, 205: {6, 54, 81, "盐矿海岸"}, 206: {6, 54, 81, "盐矿海岸"}, 207: {0, 24, 26, "危险海"}, 208: {189, 193, 198, "水中木"}, 247: {42, 42, 44, "空"}, } // 初始化实体颜色映射 g.entityColors = map[string]color.Color{ "evergreen": color.RGBA{0, 100, 0, 255}, "deciduoustree": color.RGBA{34, 139, 34, 255}, "rock1": color.RGBA{128, 128, 128, 255}, "rock2": color.RGBA{169, 169, 169, 255}, "sapling": color.RGBA{144, 238, 144, 255}, "grass": color.RGBA{124, 252, 0, 255}, "berrybush": color.RGBA{255, 0, 0, 255}, "berrybush2": color.RGBA{220, 20, 60, 255}, "spiderden": color.RGBA{128, 0, 128, 255}, "pond": color.RGBA{0, 191, 255, 255}, "rabbithole": color.RGBA{139, 69, 19, 255}, "cave": color.RGBA{105, 105, 105, 255}, "reeds": color.RGBA{189, 183, 107, 255}, "marsh_tree": color.RGBA{85, 107, 47, 255}, "marsh_bush": color.RGBA{107, 142, 35, 255}, "carrot": color.RGBA{255, 140, 0, 255}, "flower": color.RGBA{255, 192, 203, 255}, "wormhole": color.RGBA{138, 43, 226, 255}, "pighouse": color.RGBA{255, 160, 122, 255}, "mound": color.RGBA{160, 82, 45, 255}, "ruins": color.RGBA{119, 136, 153, 255}, "fireflies": color.RGBA{255, 255, 0, 255}, } return g } // ReadSaveFile 读取存档文件 func (g *DSTMapGenerator) ReadSaveFile(filePath string) (string, error) { content, err := ioutil.ReadFile(filePath) if err != nil { return "", fmt.Errorf("读取文件失败: %v", err) } // 使用正则表达式提取地图数据 re := regexp.MustCompile(`tiles="([^"]+)"`) matches := re.FindSubmatch(content) if len(matches) < 2 { return "", fmt.Errorf("无法在存档中找到地图数据") } base64Data := string(matches[1]) fmt.Printf("提取的base64数据长度: %d\n", len(base64Data)) return base64Data, nil } func RestoreTileId(original int, colors map[int]Color) int { high := original >> 8 low := original & 0xFF // 1) 直接用 high(正常情形:tile 存为 high<<8) if _, ok := colors[high]; ok { return high } // 2) 尝试 high-1 if high > 0 { if _, ok := colors[high-1]; ok { return high - 1 } } // 3) ocean 等大型 ID 区间的保守尝试(0xC8 = 200) // 如果 high 在 0xC8..0xFF 范围,优先把它当作 200+ 值尝试映射 if high >= 0xC8 && high <= 0xFF { cand := 200 + (high - 0xC8) if _, ok := colors[cand]; ok { return cand } } // 4) 其它情况:如果低字节不为0,有可能这不是简单的 high<<8 编码, // 你可以在此加入额外规则;暂时返回 0(或你想要的默认) _ = low // 如果以后需要可利用 low 做更精细的判断 return 0 } // DecodeMapData 解码地图数据 func (g *DSTMapGenerator) DecodeMapData(tilesBase64 string) ([]int, error) { tileBytes, err := base64.StdEncoding.DecodeString(tilesBase64) if err != nil { return nil, fmt.Errorf("base64解码失败: %v", err) } // 处理文件头 dataStart := 0 if len(tileBytes) > 5 && string(tileBytes[:5]) == "VRSTN" { dataStart = 5 for dataStart < len(tileBytes) && tileBytes[dataStart] == 0 { dataStart++ } } tileBytes = tileBytes[dataStart:] if len(tileBytes)%2 != 0 { tileBytes = tileBytes[:len(tileBytes)-1] } // 解码tile IDs tileIds := make([]int, 0, len(tileBytes)/2) for i := 0; i < len(tileBytes); i += 2 { if i+1 >= len(tileBytes) { break } tileId := (int(tileBytes[i+1]) << 8) | int(tileBytes[i]) tileId = RestoreTileId(tileId, g.tileColors) tileIds = append(tileIds, tileId) } // 打印分布情况 tileCounts := make(map[int]int) for _, id := range tileIds { tileCounts[id]++ } total := len(tileIds) fmt.Println("\n瓦片分布情况:") for id, count := range tileCounts { percentage := float64(count) / float64(total) * 100 if percentage > 0.01 { fmt.Printf("瓦片ID %d: %d 个 (%.2f%%)\n", id, count, percentage) } } return tileIds, nil } // CreateMapImage 创建地图图像 func (g *DSTMapGenerator) CreateMapImage(tileIds []int, width, height, scale int) *image.RGBA { img := image.NewRGBA(image.Rect(0, 0, width*scale, height*scale)) // 填充地形颜色 for y := 0; y < height; y++ { for x := 0; x < width; x++ { idx := y*width + x if idx >= len(tileIds) { continue } tileId := tileIds[idx] tileColor, exists := g.tileColors[tileId] if !exists { // 使用默认颜色 (黑色) tileColor = Color{0, 0, 0, "未知地形"} } // 翻转X坐标 flippedX := width - x - 1 // 按 scale 填充方块 for dy := 0; dy < scale; dy++ { for dx := 0; dx < scale; dx++ { img.Set(flippedX*scale+dx, y*scale+dy, color.RGBA{ R: tileColor.R, G: tileColor.G, B: tileColor.B, A: 255, }) } } } } return img } // GenerateMap 生成完整的地图 func (g *DSTMapGenerator) GenerateMap(saveFilePath, outputPath string, width, height int) error { // 读取并解码地图数据 tilesBase64, err := g.ReadSaveFile(saveFilePath) if err != nil { return err } tileIds, err := g.DecodeMapData(tilesBase64) if err != nil { return err } // 确保生成的图像为指定的宽度和高度 fmt.Printf("生成的地图尺寸: %dx%d\n", width, height) // 创建地图图像 img := g.CreateMapImage(tileIds, width, height, 16) // 保存图像 f, err := os.Create(outputPath) if err != nil { return fmt.Errorf("创建输出文件失败: %v", err) } defer f.Close() if err := png.Encode(f, img); err != nil { return fmt.Errorf("保存图像失败: %v", err) } fmt.Printf("地图已保存到: %s\n", outputPath) return nil } // ExtractDimensions 从文件中读取并提取 height 和 width func ExtractDimensions(filePath string) (int, int, error) { // 读取文件内容 data, err := ioutil.ReadFile(filePath) if err != nil { return 0, 0, err } // 将文件内容转换为字符串 input := string(data) // 定义正则表达式 heightRegex := regexp.MustCompile(`height=(\d+)`) widthRegex := regexp.MustCompile(`width=(\d+)`) // 查找匹配 heightMatch := heightRegex.FindStringSubmatch(input) widthMatch := widthRegex.FindStringSubmatch(input) // 返回结果 var height, width int if len(heightMatch) > 1 { fmt.Sscanf(heightMatch[1], "%d", &height) } else { height = 0 // 未找到时返回 0 } if len(widthMatch) > 1 { fmt.Sscanf(widthMatch[1], "%d", &width) } else { width = 0 // 未找到时返回 0 } return height, width, nil } // WalrusHut_Plains func main() { filePath := "save/session/50D0753A78BF681E/0000000004" height, width, err := ExtractDimensions(filePath) if err != nil { fmt.Println("Error:", err) return } generator := NewDSTMapGenerator() err = generator.GenerateMap( filePath, "dst_map.png", height, // 指定宽度 width, // 指定高度 ) if err != nil { fmt.Printf("生成地图时出错: %v\n", err) os.Exit(1) } } ================================================ FILE: internal/service/dstPath/dst_path.go ================================================ package dstPath import ( "dst-admin-go/internal/service/dstConfig" "fmt" "path/filepath" "runtime" "strings" ) type DstPath interface { UpdateCommand(clusterName string) (string, error) } func EscapePath(path string) string { if runtime.GOOS == "windows" { return path } // 在这里添加需要转义的特殊字符 escapedChars := []string{" ", "'", "(", ")"} for _, char := range escapedChars { path = strings.ReplaceAll(path, char, "\\"+char) } return path } func GetBaseUpdateCmd(cluster dstConfig.DstConfig) string { steamCmdPath := cluster.Steamcmd dstInstallDir := cluster.Force_install_dir if cluster.Beta == 1 { dstInstallDir = dstInstallDir + "-beta" } // 确保路径是跨平台兼容的 dstInstallDir = filepath.Clean(EscapePath(dstInstallDir)) steamCmdPath = filepath.Clean(steamCmdPath) // 构建基本命令 baseCmd := "+login anonymous +force_install_dir %s +app_update 343050" if cluster.Beta == 1 { baseCmd += " -beta updatebeta" } baseCmd += " validate +quit" baseCmd = fmt.Sprintf(baseCmd, dstInstallDir) return baseCmd } ================================================ FILE: internal/service/dstPath/linux_dst.go ================================================ package dstPath import ( "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/dstConfig" "fmt" "path/filepath" ) type LinuxDstPath struct { dstConfig dstConfig.Config } func NewLinuxDstPath(dstConfig dstConfig.Config) *LinuxDstPath { return &LinuxDstPath{dstConfig: dstConfig} } func (d LinuxDstPath) UpdateCommand(clusterName string) (string, error) { cluster, err := d.dstConfig.GetDstConfig(clusterName) if err != nil { return "", err } steamCmdPath := cluster.Steamcmd baseCmd := GetBaseUpdateCmd(cluster) var cmd string steamCmdScript := filepath.Join(steamCmdPath, "steamcmd.sh") if cluster.Bin == 86 { cmd = fmt.Sprintf("cd %s ; box86 ./linux32/steamcmd %s", steamCmdPath, baseCmd) } else { if fileUtils.Exists(steamCmdScript) { cmd = fmt.Sprintf("cd %s ; ./steamcmd.sh %s", steamCmdPath, baseCmd) } else { cmd = fmt.Sprintf("cd %s ; ./steamcmd %s", steamCmdPath, baseCmd) } } return cmd, nil } ================================================ FILE: internal/service/dstPath/window_dst.go ================================================ package dstPath import ( "dst-admin-go/internal/service/dstConfig" "fmt" ) type WindowDstPath struct { dstConfig dstConfig.Config } func NewWindowDst(dstConfig dstConfig.Config) *WindowDstPath { return &WindowDstPath{dstConfig: dstConfig} } func (d WindowDstPath) UpdateCommand(clusterName string) (string, error) { cluster, err := d.dstConfig.GetDstConfig(clusterName) if err != nil { return "", err } steamCmdPath := cluster.Steamcmd baseCmd := GetBaseUpdateCmd(cluster) var cmd string cmd = fmt.Sprintf("cd /d %s && Start steamcmd.exe %s", steamCmdPath, baseCmd) return cmd, nil } ================================================ FILE: internal/service/game/factory.go ================================================ package game import ( "dst-admin-go/internal/service/dstConfig" "dst-admin-go/internal/service/levelConfig" "runtime" ) func NewGame(dstConfig dstConfig.Config, levelConfigUtils *levelConfig.LevelConfigUtils) Process { if runtime.GOOS == "windows" { return NewWindowProcess(&dstConfig, levelConfigUtils) } return NewLinuxProcess(dstConfig, levelConfigUtils) } ================================================ FILE: internal/service/game/linux_process.go ================================================ package game import ( "dst-admin-go/internal/pkg/utils/dstUtils" "dst-admin-go/internal/pkg/utils/shellUtils" "dst-admin-go/internal/service/dstConfig" "dst-admin-go/internal/service/levelConfig" "log" "strings" "sync" "time" ) type LinuxProcess struct { dstConfig dstConfig.Config levelConfigUtils *levelConfig.LevelConfigUtils mu sync.Mutex // 保护启动/停止操作,防止并发执行 } func NewLinuxProcess(dstConfig dstConfig.Config, levelConfigUtils *levelConfig.LevelConfigUtils) *LinuxProcess { return &LinuxProcess{ dstConfig: dstConfig, levelConfigUtils: levelConfigUtils, } } func (p *LinuxProcess) SessionName(clusterName, levelName string) string { return "DST_8level_" + levelName + "_" + clusterName } func (p *LinuxProcess) Start(clusterName, levelName string) error { p.mu.Lock() defer p.mu.Unlock() err := p.stop(clusterName, levelName) if err != nil { return err } return p.launchLevel(clusterName, levelName) } func (p *LinuxProcess) launchLevel(clusterName, levelName string) error { cluster, err := p.dstConfig.GetDstConfig(clusterName) if err != nil { return err } bin := cluster.Bin dstInstallDir := cluster.Force_install_dir if cluster.Beta == 1 { dstInstallDir = dstInstallDir + "-beta" } ugcDirectory := cluster.Ugc_directory persistent_storage_root := cluster.Persistent_storage_root conf_dir := cluster.Conf_dir var startCmd = "" dstInstallDir = dstUtils.EscapePath(dstInstallDir) log.Println(dstInstallDir) sessionName := p.SessionName(clusterName, levelName) if bin == 64 { startCmd = "cd " + dstInstallDir + "/bin64 ; screen -d -m -S \"" + sessionName + "\" ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster " + clusterName + " -shard " + levelName } else if bin == 100 { startCmd = "cd " + dstInstallDir + "/bin64 ; screen -d -m -S \"" + sessionName + "\" ./dontstarve_dedicated_server_nullrenderer_x64_luajit -console -cluster " + clusterName + " -shard " + levelName } else if bin == 86 { startCmd = "cd " + dstInstallDir + "/bin64 ; screen -d -m -S \"" + sessionName + "\" box86 ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster " + clusterName + " -shard " + levelName } else if bin == 2664 { startCmd = "cd " + dstInstallDir + "/bin64 ; screen -d -m -S \"" + sessionName + "\" box64 ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster " + clusterName + " -shard " + levelName } else { startCmd = "cd " + dstInstallDir + "/bin ; screen -d -m -S \"" + sessionName + "\" ./dontstarve_dedicated_server_nullrenderer -console -cluster " + clusterName + " -shard " + levelName } if ugcDirectory != "" { startCmd += " -ugc_directory " + ugcDirectory } if persistent_storage_root != "" { startCmd += " -persistent_storage_root " + persistent_storage_root } if conf_dir != "" { startCmd += " -conf_dir " + conf_dir } startCmd += " ;" log.Println("正在启动世界", "cluster: ", clusterName, "level: ", levelName, "command: ", startCmd) _, err = shellUtils.Shell(startCmd) return err } func (p *LinuxProcess) shutdownLevel(clusterName, levelName string) error { ok, err := p.Status(clusterName, levelName) if err != nil { return err } if !ok { return nil } shell := "screen -S \"" + p.SessionName(clusterName, levelName) + "\" -p 0 -X stuff \"c_shutdown(true)\\n\"" log.Println("正在shutdown世界", "cluster: ", clusterName, "level: ", levelName, "command: ", shell) _, err = shellUtils.Shell(shell) return err } func (p *LinuxProcess) killLevel(clusterName, level string) error { if ok, err := p.Status(clusterName, level); err != nil || !ok { return nil } cmd := " ps -ef | grep -v grep | grep -v tail |grep '" + clusterName + "'|grep " + level + " |sed -n '1P'|awk '{print $2}' |xargs kill -9" log.Println("正在kill世界", "cluster: ", clusterName, "level: ", level, "command: ", cmd) _, err := shellUtils.Shell(cmd) return err } func (p *LinuxProcess) Stop(clusterName, levelName string) error { p.mu.Lock() defer p.mu.Unlock() return p.stop(clusterName, levelName) } // stop 内部实现,不加锁,供 Start 等方法内部调用 func (p *LinuxProcess) stop(clusterName, levelName string) error { p.shutdownLevel(clusterName, levelName) time.Sleep(3 * time.Second) if ok, err := p.Status(clusterName, levelName); err == nil && ok { var i uint8 = 1 for { if ok, err := p.Status(clusterName, levelName); err == nil && ok { break } p.shutdownLevel(clusterName, levelName) log.Println("正在第", i, "次stop世界", "cluster: ", clusterName, "level: ", levelName) time.Sleep(1 * time.Second) i++ if i > 3 { break } } } log.Println("使用kill命令强制结束世界", "cluster: ", clusterName, "level: ", levelName) return p.killLevel(clusterName, levelName) } func (p *LinuxProcess) StartAll(clusterName string) error { p.mu.Lock() defer p.mu.Unlock() err := p.stopAll(clusterName) if err != nil { return err } config, err := p.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { return err } var wg sync.WaitGroup wg.Add(len(config.LevelList)) for i := range config.LevelList { go func(i int) { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() levelName := config.LevelList[i].File err := p.launchLevel(clusterName, levelName) if err != nil { log.Println(err) return } }(i) } ClearScreen() wg.Wait() return nil } func (p *LinuxProcess) StopAll(clusterName string) error { p.mu.Lock() defer p.mu.Unlock() return p.stopAll(clusterName) } // stopAll 内部实现,不加锁,供 StartAll 等方法内部调用 func (p *LinuxProcess) stopAll(clusterName string) error { config, err := p.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { log.Panicln(err) } var wg sync.WaitGroup wg.Add(len(config.LevelList)) for i := range config.LevelList { go func(i int) { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() levelName := config.LevelList[i].File err := p.stop(clusterName, levelName) if err != nil { return } }(i) } wg.Wait() return nil } func (p *LinuxProcess) Status(clusterName, levelName string) (bool, error) { cmd := " ps -ef | grep -v grep | grep -v tail |grep '" + clusterName + "'|grep " + levelName + " |sed -n '1P'|awk '{print $2}' " result, err := shellUtils.Shell(cmd) if err != nil { return false, nil } res := strings.Split(result, "\n")[0] return res != "", nil } func (p *LinuxProcess) Command(clusterName, levelName, command string) error { cmd := "screen -S \"" + p.SessionName(clusterName, levelName) + "\" -p 0 -X stuff \"" + command + "\\n\"" _, err := shellUtils.Shell(cmd) return err } func (p *LinuxProcess) PsAuxSpecified(clusterName, levelName string) DstPsAux { dstPsAux := DstPsAux{} cmd := "ps -aux | grep -v grep | grep -v tail | grep " + clusterName + " | grep " + levelName + " | sed -n '2P' |awk '{print $3, $4, $5, $6}'" info, err := shellUtils.Shell(cmd) if err != nil { log.Println(cmd + " error: " + err.Error()) return dstPsAux } if info == "" { return dstPsAux } arr := strings.Split(info, " ") dstPsAux.CpuUage = strings.Replace(arr[0], "\n", "", -1) dstPsAux.MemUage = strings.Replace(arr[1], "\n", "", -1) dstPsAux.VSZ = strings.Replace(arr[2], "\n", "", -1) dstPsAux.RSS = strings.Replace(arr[3], "\n", "", -1) return dstPsAux } const ( // ClearScreenCmd 检查目前所有的screen作业,并删除已经无法使用的screen作业 ClearScreenCmd = "screen -wipe " ) func ClearScreen() bool { result, err := shellUtils.Shell(ClearScreenCmd) if err != nil { return false } res := strings.Split(result, "\n")[0] return res != "" } ================================================ FILE: internal/service/game/process.go ================================================ package game type DstPsAux struct { CpuUage string `json:"cpuUage"` MemUage string `json:"memUage"` VSZ string `json:"VSZ"` RSS string `json:"RSS"` } type Process interface { SessionName(clusterName, levelName string) string Start(clusterName, levelName string) error Stop(clusterName, levelName string) error StartAll(clusterName string) error StopAll(clusterName string) error Status(clusterName, levelName string) (bool, error) Command(clusterName, levelName, command string) error PsAuxSpecified(clusterName, levelName string) DstPsAux } ================================================ FILE: internal/service/game/windowGameCli.go ================================================ //package game // //import ( // "bufio" // "fmt" // "io" // "log" // "os" // "os/exec" // "strings" // "sync" // "sync/atomic" // "time" // // "github.com/shirou/gopsutil/process" //) // //type ClusterContainer struct { // container map[string]*LevelInstance // lock sync.RWMutex //} // //func NewClusterContainer() *ClusterContainer { // return &ClusterContainer{ // container: map[string]*LevelInstance{}, // } //} // //func (receiver *ClusterContainer) StartLevel(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir string) { // receiver.lock.Lock() // // key := cluster + "_" + levelName // log.Println("正在启动 ", key) // value, ok := receiver.container[key] // if !ok { // value = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir) // receiver.container[key] = value // } else { // if value.dstSeverInstall != dstServerInstall { // // 直接删除,避免死锁(不调用 Remove) // delete(receiver.container, key) // value = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir) // receiver.container[key] = value // } // } // // 在锁外启动,避免长时间持有锁 // receiver.lock.Unlock() // value.Start() //} // //func (receiver *ClusterContainer) StopLevel(cluster, levelName string) { // receiver.lock.RLock() // defer receiver.lock.RUnlock() // // key := cluster + "_" + levelName // value, ok := receiver.container[key] // log.Println("正在停止世界", cluster, levelName) // if ok { // value.Stop() // } //} // //func (receiver *ClusterContainer) Send(cluster, levelName, message string) { // receiver.lock.RLock() // defer receiver.lock.RUnlock() // // key := cluster + "_" + levelName // value, ok := receiver.container[key] // if ok { // value.Send(message) // } //} // //func (receiver *ClusterContainer) Status(cluster, levelName string) bool { // receiver.lock.RLock() // defer receiver.lock.RUnlock() // // key := cluster + "_" + levelName // value, ok := receiver.container[key] // if ok { // return value.Status() // } // return false //} // //func (receiver *ClusterContainer) MemUsage(cluster, levelName string) float64 { // receiver.lock.RLock() // defer receiver.lock.RUnlock() // // key := cluster + "_" + levelName // value, ok := receiver.container[key] // if ok { // return value.GetProcessMemInfo() // } // return 0 //} // //func (receiver *ClusterContainer) CpuUsage(cluster, levelName string) float64 { // receiver.lock.RLock() // defer receiver.lock.RUnlock() // // key := cluster + "_" + levelName // value, ok := receiver.container[key] // if ok { // return value.GetProcessCpuInfo() // } // return 0 //} // //func (receiver *ClusterContainer) Remove(cluster, levelName string) { // receiver.lock.Lock() // defer receiver.lock.Unlock() // key := cluster + "_" + levelName // delete(receiver.container, key) //} // //type LevelInstance struct { // running atomic.Bool // lock sync.Mutex // stdin io.WriteCloser // stdout io.ReadCloser // pid int // // cluster string // levelName string // bin int // steamcmd string // dstSeverInstall string // ugc_directory string // persistent_storage_root string // conf_dir string //} // //func NewLevelInstance(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugc_directory, persistent_storage_root, conf_dir string) *LevelInstance { // return &LevelInstance{ // cluster: cluster, // levelName: levelName, // bin: bin, // steamcmd: steamcmd, // dstSeverInstall: dstServerInstall, // ugc_directory: ugc_directory, // persistent_storage_root: persistent_storage_root, // conf_dir: conf_dir, // } //} // //func (receiver *LevelInstance) Status() bool { // return receiver.running.Load() //} // //func (receiver *LevelInstance) Start() { // receiver.lock.Lock() // // // 锁内检查,避免竞态条件 // if receiver.running.Load() == true { // receiver.lock.Unlock() // return // } // // // 创建输出文件 // tLogsTxt := receiver.cluster + "_" + receiver.levelName + "_log" // logFile, err := os.Create(tLogsTxt) // if err != nil { // log.Println("Error creating log file:", err) // receiver.lock.Unlock() // return // } // defer func(logFile *os.File) { // err := logFile.Close() // if err != nil { // log.Println("Error closing log file:", err) // } // }(logFile) // // var args []string // if receiver.bin == 32 { // args = append(args, "./dontstarve_dedicated_server_nullrenderer.exe") // } else { // args = append(args, "./dontstarve_dedicated_server_nullrenderer_x64.exe") // } // args = append(args, "-console") // args = append(args, "-cluster") // args = append(args, receiver.cluster) // args = append(args, "-shard") // args = append(args, receiver.levelName) // if receiver.persistent_storage_root != "" { // args = append(args, "-persistent_storage_root") // args = append(args, receiver.persistent_storage_root) // } // if receiver.conf_dir != "" { // args = append(args, "-conf_dir") // args = append(args, receiver.conf_dir) // } // if receiver.ugc_directory != "" { // args = append(args, "-ugc_directory") // args = append(args, receiver.ugc_directory) // } // // 创建一个 cmd 对象 // cmd := exec.Command(args[0], args[1:]...) // if receiver.bin == 32 { // cmd.Dir = receiver.dstSeverInstall + "\\bin" // } else { // cmd.Dir = receiver.dstSeverInstall + "\\bin64" // } // // receiver.running.Store(true) // receiver.lock.Unlock() // // // 获取子进程的 stdin、stdout 和 stderr // receiver.stdin, err = cmd.StdinPipe() // if err != nil { // log.Printf("Error getting stdin pipe: %v\n", err) // receiver.running.Store(false) // return // } // receiver.stdout, err = cmd.StdoutPipe() // if err != nil { // log.Printf("Error getting stdout pipe: %v\n", err) // receiver.running.Store(false) // return // } // stderr, err := cmd.StderrPipe() // if err != nil { // log.Printf("Error getting stderr pipe: %v\n", err) // receiver.running.Store(false) // return // } // // // 启动子进程 // if err := cmd.Start(); err != nil { // fmt.Printf("Error starting command: %v\n", err) // receiver.running.Store(false) // return // } // // receiver.pid = cmd.Process.Pid // // 开启 goroutine 实时读取子进程的输出并写入文件和控制台 // go func() { // _, _ = io.Copy(io.MultiWriter(os.Stdout, logFile), receiver.stdout) // }() // go func() { // _, _ = io.Copy(io.MultiWriter(os.Stderr, logFile), stderr) // }() // // // 等待子进程退出 // if err := cmd.Wait(); err != nil { // log.Printf("Error waiting for command: %v\n", err) // if receiver.stdin != nil { // _ = receiver.stdin.Close() // } // if receiver.stdout != nil { // _ = receiver.stdout.Close() // } // receiver.running.Store(false) // } // log.Println("process exit !!!") // receiver.running.Store(false) //} // //func (receiver *LevelInstance) Stop() { // receiver.lock.Lock() // defer receiver.lock.Unlock() // // if receiver.running.Load() == true { // err := receiver.Send("c_shutdown(true)") // if err != nil { // log.Println("stop game error", err) // } else { // receiver.running.Store(false) // } // } //} // //func (receiver *LevelInstance) Send(cmd string) error { // // 向子进程写入命令 // writer := bufio.NewWriter(receiver.stdin) // log.Println("cmd: ", cmd) // cmd = strings.Replace(cmd, "\\", "", -1) // input := cmd + "\n" // _, err := writer.WriteString(input) // if err != nil { // log.Printf("Error writing to stdin: %v\n", err) // return err // } // err = writer.Flush() // if err != nil { // return err // } // return nil //} // //func (receiver *LevelInstance) GetProcessMemInfo() float64 { // p, err := process.NewProcess(int32(receiver.pid)) // if err != nil { // fmt.Println("Error getting process info:", err) // return 0 // } // // 获取内存使用情况 // memInfo, err := p.MemoryInfo() // if err != nil { // fmt.Println("Error getting memory info:", err) // return 0 // } // memUsage := float64(memInfo.RSS) / (1024 * 1024) // 以 MB 为单位 // return memUsage //} // //func (receiver *LevelInstance) GetProcessCpuInfo() float64 { // p, err := process.NewProcess(int32(receiver.pid)) // if err != nil { // fmt.Println("Error getting process info:", err) // return 0 // } // // 获取 CPU 使用情况 // cpuPercent, err := p.Percent(time.Second) // if err != nil { // fmt.Println("Error getting CPU percent:", err) // return 0 // } // return cpuPercent //} package game import ( "bufio" "fmt" "io" "log" "os" "os/exec" "strings" "sync" "sync/atomic" "time" "github.com/shirou/gopsutil/process" ) type ClusterContainer struct { container map[string]*LevelInstance lock sync.RWMutex } func NewClusterContainer() *ClusterContainer { return &ClusterContainer{ container: map[string]*LevelInstance{}, lock: sync.RWMutex{}, } } func (receiver *ClusterContainer) StartLevel(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir string) { //receiver.lock.Lock() //defer receiver.lock.Unlock() key := cluster + "_" + levelName log.Println("正在启动 ", key) value, ok := receiver.container[key] if !ok { value = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir) receiver.container[key] = value } else { if value.dstSeverInstall != dstServerInstall { receiver.Remove(cluster, levelName) value = NewLevelInstance(cluster, levelName, bin, steamcmd, dstServerInstall, ugcDirectory, persistent_storage_root, conf_dir) receiver.container[key] = value } } value.Start() } func (receiver *ClusterContainer) StopLevel(cluster, levelName string) { key := cluster + "_" + levelName value, ok := receiver.container[key] log.Println("正在停止世界", cluster, levelName) if ok { value.Stop() } } func (receiver *ClusterContainer) Send(cluster, levelName, message string) { key := cluster + "_" + levelName value, ok := receiver.container[key] if ok { value.Send(message) } } func (receiver *ClusterContainer) Status(cluster, levelName string) bool { key := cluster + "_" + levelName value, ok := receiver.container[key] if ok { return value.Status() } return false } func (receiver *ClusterContainer) MemUsage(cluster, levelName string) float64 { key := cluster + "_" + levelName value, ok := receiver.container[key] if ok { return value.GetProcessMemInfo() } return 0 } func (receiver *ClusterContainer) CpuUsage(cluster, levelName string) float64 { key := cluster + "_" + levelName value, ok := receiver.container[key] if ok { return value.GetProcessCpuInfo() } return 0 } func (receiver *ClusterContainer) Remove(cluster, levelName string) { receiver.lock.RLock() defer receiver.lock.RUnlock() key := cluster + "_" + levelName delete(receiver.container, key) } type LevelInstance struct { running atomic.Bool lock sync.Mutex stdin io.WriteCloser stdout io.ReadCloser pid int cluster string levelName string bin int steamcmd string dstSeverInstall string ugc_directory string persistent_storage_root string conf_dir string } func NewLevelInstance(cluster, levelName string, bin int, steamcmd, dstServerInstall, ugc_directory, persistent_storage_root, conf_dir string) *LevelInstance { running := atomic.Bool{} running.Store(false) game := &LevelInstance{ lock: sync.Mutex{}, running: running, cluster: cluster, levelName: levelName, bin: bin, steamcmd: steamcmd, dstSeverInstall: dstServerInstall, ugc_directory: ugc_directory, persistent_storage_root: persistent_storage_root, conf_dir: conf_dir, } return game } func (receiver *LevelInstance) Status() bool { return receiver.running.Load() } func (receiver *LevelInstance) Start() { if receiver.running.Load() == true { return } receiver.lock.Lock() // 创建输出文件 tLogsTxt := receiver.cluster + "_" + receiver.levelName + "_log" logFile, err := os.Create(tLogsTxt) if err != nil { log.Println("Error creating log file:", err) return } defer func(logFile *os.File) { err := logFile.Close() if err != nil { receiver.lock.Unlock() } }(logFile) var args []string if receiver.bin == 32 { args = append(args, "./dontstarve_dedicated_server_nullrenderer.exe") } else { args = append(args, "./dontstarve_dedicated_server_nullrenderer_x64.exe") } args = append(args, "-console") args = append(args, "-cluster") args = append(args, receiver.cluster) args = append(args, "-shard") args = append(args, receiver.levelName) if receiver.persistent_storage_root != "" { args = append(args, "-persistent_storage_root") args = append(args, receiver.persistent_storage_root) } if receiver.conf_dir != "" { args = append(args, "-conf_dir") args = append(args, receiver.conf_dir) } if receiver.ugc_directory != "" { args = append(args, "-ugc_directory") args = append(args, receiver.ugc_directory) } // 创建一个 cmd 对象 cmd := exec.Command(args[0], args[1:]...) if receiver.bin == 32 { cmd.Dir = receiver.dstSeverInstall + "\\bin" } else { cmd.Dir = receiver.dstSeverInstall + "\\bin64" } receiver.running.Store(true) receiver.lock.Unlock() // 获取子进程的 stdin、stdout 和 stderr receiver.stdin, err = cmd.StdinPipe() if err != nil { log.Printf("Error getting stdin pipe: %v\n", err) return } receiver.stdout, err = cmd.StdoutPipe() if err != nil { log.Printf("Error getting stdout pipe: %v\n", err) return } stderr, err := cmd.StderrPipe() if err != nil { log.Printf("Error getting stderr pipe: %v\n", err) return } // 启动子进程 if err := cmd.Start(); err != nil { fmt.Printf("Error starting command: %v\n", err) return } receiver.pid = cmd.Process.Pid // 开启 goroutine 实时读取子进程的输出并写入文件和控制台 go func() { io.Copy(io.MultiWriter(os.Stdout, logFile), receiver.stdout) }() go func() { io.Copy(io.MultiWriter(os.Stderr, logFile), stderr) }() // 等待子进程退出 if err := cmd.Wait(); err != nil { log.Printf("Error waiting for command: %v\n", err) if receiver.stdin != nil { receiver.stdin.Close() } if receiver.stdout != nil { receiver.stdout.Close() } receiver.running.Store(false) } log.Println("process exit !!!") receiver.running.Store(false) } func (receiver *LevelInstance) Stop() { receiver.lock.Lock() defer receiver.lock.Unlock() if receiver.running.Load() == true { err := receiver.Send("c_shutdown(true)") if err != nil { log.Println("stop game error", err) } else { receiver.running.Store(false) } } } func (receiver *LevelInstance) Send(cmd string) error { // 向子进程写入命令 writer := bufio.NewWriter(receiver.stdin) log.Println("cmd: ", cmd) cmd = strings.Replace(cmd, "\\", "", -1) input := cmd + "\n" _, err := writer.WriteString(input) if err != nil { log.Printf("Error writing to stdin: %v\n", err) return err } err = writer.Flush() if err != nil { return err } return nil } func (receiver *LevelInstance) GetProcessMemInfo() float64 { p, err := process.NewProcess(int32(receiver.pid)) if err != nil { fmt.Println("Error getting process info:", err) return 0 } // 获取内存使用情况 memInfo, err := p.MemoryInfo() if err != nil { fmt.Println("Error getting memory info:", err) return 0 } memUsage := float64(memInfo.RSS) / (1024 * 1024) // 以 MB 为单位 return memUsage } func (receiver *LevelInstance) GetProcessCpuInfo() float64 { p, err := process.NewProcess(int32(receiver.pid)) if err != nil { fmt.Println("Error getting process info:", err) return 0 } // 获取 CPU 使用情况 cpuPercent, err := p.Percent(time.Second) if err != nil { fmt.Println("Error getting CPU percent:", err) return 0 } return cpuPercent } ================================================ FILE: internal/service/game/window_process.go ================================================ package game import ( "dst-admin-go/internal/service/dstConfig" "dst-admin-go/internal/service/levelConfig" "fmt" "log" "sync" ) type WindowProcess struct { dstConfig dstConfig.Config cli *ClusterContainer levelConfigUtils *levelConfig.LevelConfigUtils } func NewWindowProcess(dstConfig *dstConfig.Config, levelConfigUtils *levelConfig.LevelConfigUtils) *WindowProcess { return &WindowProcess{ dstConfig: *dstConfig, cli: NewClusterContainer(), levelConfigUtils: levelConfigUtils, } } func (p *WindowProcess) SessionName(clusterName, levelName string) string { return clusterName + "_" + levelName } func (p *WindowProcess) Start(clusterName, levelName string) error { config, err := p.dstConfig.GetDstConfig(clusterName) if err != nil { return err } go func() { p.cli.StartLevel(clusterName, levelName, config.Bin, config.Steamcmd, config.Force_install_dir, config.Ugc_directory, config.Persistent_storage_root, config.Conf_dir) }() return err } func (p *WindowProcess) Stop(clusterName, levelName string) error { p.cli.StopLevel(clusterName, levelName) return nil } func (p *WindowProcess) StartAll(clusterName string) error { err := p.StopAll(clusterName) if err != nil { return err } config, err := p.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { log.Panicln(err) } var wg sync.WaitGroup wg.Add(len(config.LevelList)) for i := range config.LevelList { go func(i int) { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() levelName := config.LevelList[i].File err := p.Start(clusterName, levelName) if err != nil { log.Println(err) return } }(i) } wg.Wait() return nil } func (p *WindowProcess) StopAll(clusterName string) error { config, err := p.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { log.Panicln(err) } var wg sync.WaitGroup wg.Add(len(config.LevelList)) for i := range config.LevelList { go func(i int) { defer func() { wg.Done() if r := recover(); r != nil { log.Println(r) } }() levelName := config.LevelList[i].File err := p.Stop(clusterName, levelName) if err != nil { return } }(i) } wg.Wait() return nil } func (p *WindowProcess) Status(clusterName, levelName string) (bool, error) { return p.cli.Status(clusterName, levelName), nil } func (p *WindowProcess) Command(clusterName, levelName, command string) error { p.cli.Send(clusterName, levelName, command) return nil } func (p *WindowProcess) PsAuxSpecified(clusterName, levelName string) DstPsAux { cpuUsage := p.cli.CpuUsage(clusterName, levelName) memUsage := p.cli.MemUsage(clusterName, levelName) dstPsAux := DstPsAux{} dstPsAux.RSS = fmt.Sprintf("%f", memUsage*1024) dstPsAux.CpuUage = fmt.Sprintf("%f", cpuUsage) return dstPsAux } ================================================ FILE: internal/service/gameArchive/game_archive.go ================================================ package gameArchive import ( "dst-admin-go/internal/config" "dst-admin-go/internal/pkg/utils/dstUtils" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/pkg/utils/luaUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/gameConfig" "dst-admin-go/internal/service/level" "fmt" "io/ioutil" "net" "net/http" "os" "path" "path/filepath" "reflect" "regexp" "strconv" "strings" "sync" "time" ) type GameArchive struct { gameConfig *gameConfig.GameConfig level *level.LevelService archive *archive.PathResolver } func NewGameArchive(gameConfig *gameConfig.GameConfig, level *level.LevelService, archive *archive.PathResolver) *GameArchive { return &GameArchive{ gameConfig: gameConfig, level: level, archive: archive, } } type GameArchiveInfo struct { ClusterName string `json:"clusterName"` ClusterDescription string `json:"clusterDescription"` ClusterPassword string `json:"clusterPassword"` GameMod string `json:"gameMod"` MaxPlayers int `json:"maxPlayers"` Mods int `json:"mods"` IpConnect string `json:"ipConnect"` Port uint `json:"port"` Ip string `json:"ip"` Meta Meta `json:"meta"` Version int64 `json:"version"` LastVersion int64 `json:"lastVersion"` } type Clock struct { TotalTimeInPhase int `lua:"totaltimeinphase"` Cycles int `lua:"cycles"` Phase string `lua:"phase"` RemainingTimeInPhase float64 `lua:"remainingtimeinphase"` MooomPhaseCycle int `lua:"mooomphasecycle"` Segs Segs `lua:"segs"` } type Segs struct { Night int `lua:"night"` Day int `lua:"day"` Dusk int `lua:"dusk"` } type IsRandom struct { Summer bool `lua:"summer"` Autumn bool `lua:"autumn"` Spring bool `lua:"spring"` Winter bool `lua:"winter"` } type Lengths struct { Summer int `lua:"summer"` Autumn int `lua:"autumn"` Spring int `lua:"spring"` Winter int `lua:"winter"` } type Seasons struct { Premode bool `lua:"premode"` Season string `lua:"season"` ElapsedDaysInSeason int `lua:"elapseddaysinseason"` IsRandom IsRandom `lua:"israndom"` Lengths Lengths `lua:"lengths"` RemainingDaysInSeason int `lua:"remainingdaysinseason"` Mode string `lua:"mode"` TotalDaysInSeason int `lua:"totaldaysinseason"` Segs map[string]interface{} `lua:"segs"` } type Meta struct { Clock Clock `lua:"clock"` Seasons Seasons `lua:"seasons"` } func (d *GameArchive) GetGameArchive(clusterName string) GameArchiveInfo { var wg sync.WaitGroup wg.Add(5) gameArchie := GameArchiveInfo{} basePath := d.archive.ClusterPath(clusterName) // 获取基础信息 go func() { clusterIni, _ := d.gameConfig.GetClusterIni(clusterName) gameArchie.ClusterName = clusterIni.ClusterName gameArchie.ClusterDescription = clusterIni.ClusterDescription gameArchie.ClusterPassword = clusterIni.ClusterPassword gameArchie.GameMod = clusterIni.GameMode gameArchie.MaxPlayers = int(clusterIni.MaxPlayers) wg.Done() }() // 获取mod数量 go func() { masterModoverrides, err := fileUtils.ReadFile(path.Join(basePath, "Master", "modoverrides.lua")) if err != nil { gameArchie.Mods = 0 } else { gameArchie.Mods = len(dstUtils.WorkshopIds(masterModoverrides)) } wg.Done() }() // 获取天数和季节 go func() { defer func() { wg.Done() if r := recover(); r != nil { } }() gameArchie.Meta = d.Snapshoot(clusterName) }() // 获取直连ip go func() { defer func() { wg.Done() if r := recover(); r != nil { } }() clusterIni, _ := d.gameConfig.GetClusterIni(clusterName) password := clusterIni.ClusterPassword serverIni := d.level.GetServerIni(path.Join(basePath, "Master", "server.ini"), true) wanip := config.Cfg.WanIP if wanip != "" { } else { ipv4, err := d.GetPublicIP() if err != nil { wanip, _ = d.GetPrivateIP() } else { wanip = ipv4 } } if wanip == "" { gameArchie.IpConnect = "" } else { // c_connect("IP address", port, "password") if password != "" { gameArchie.IpConnect = "c_connect(\"" + wanip + "\"," + strconv.Itoa(int(serverIni.ServerPort)) + ",\"" + password + "\"" + ")" } else { gameArchie.IpConnect = "c_connect(\"" + wanip + "\"," + strconv.Itoa(int(serverIni.ServerPort)) + ")" } } gameArchie.Port = serverIni.ServerPort gameArchie.Ip = wanip }() go func() { defer func() { wg.Done() if r := recover(); r != nil { } }() localVersion, _ := d.archive.GetLocalDstVersion(clusterName) version, _ := d.archive.GetLastDstVersion() gameArchie.Version = localVersion gameArchie.LastVersion = version }() wg.Wait() return gameArchie } /* - 以下均是公开接口,返回纯文本数据 - 如果服务端有透明代理或者分流,可能获取到的是代理ip,优先使用能获取真实ip的接口 - 饥荒暂不支持IPv6 */ func (d *GameArchive) GetPublicIP() (string, error) { apis := [...]string{ // == 以下优先返回国内ip == "https://myip.ipip.net", "https://cdid.c-ctrip.com/model-poc2/h", // 某携程api,IPv6优先 // == 以下优先返回国外ip == "https://lobby-v2.klei.com/lobby/getIP", // Klei官方api "https://api.ipify.org", "https://ifconfig.me/ip", "https://checkip.amazonaws.com", } client := &http.Client{ Timeout: 5 * time.Second, } for _, api := range apis { resp, err := client.Get(api) if err != nil { continue } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { continue } ipv4Regex := regexp.MustCompile(`\b\d{1,3}(\.\d{1,3}){3}\b`) text := strings.TrimSpace(string(body)) if match := ipv4Regex.FindString(text); match != "" { if ip := net.ParseIP(match); ip != nil && ip.To4() != nil { return ip.String(), nil } } } return "", nil } func (d *GameArchive) GetPrivateIP() (string, error) { addrs, err := net.InterfaceAddrs() if err != nil { return "", err } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } if ipv4 := ip.To4(); ipv4 != nil { return ipv4.String(), nil } } return "", nil } func (d *GameArchive) getSubPathLevel(rootP, curPath string) int { relPath, err := filepath.Rel(rootP, curPath) if err != nil { // 如果计算相对路径时出错,说明 curPath 不是 rootP 的子目录 return -1 } // 计算相对路径中 ".." 的数量,即为层数 return strings.Count(relPath, "..") } func (d *GameArchive) FindLatestMetaFile(rootDir string) (string, error) { var latestFile string var latestModTime time.Time err := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && filepath.Ext(info.Name()) == ".meta" && d.getSubPathLevel(rootDir, path) == 2 { if info.ModTime().After(latestModTime) { latestFile = path latestModTime = info.ModTime() } } return nil }) if err != nil { return "", err } return latestFile, nil } func findLatestMetaFile(directory string) (string, error) { // 检查指定目录是否存在 _, err := os.Stat(directory) if os.IsNotExist(err) { return "", fmt.Errorf("目录不存在:%s", directory) } // 获取指定目录下一级的所有子目录 subdirs, err := ioutil.ReadDir(directory) if err != nil { return "", fmt.Errorf("读取目录失败:%s", err) } // 用于存储最新的.meta文件路径和其修改时间 var latestMetaFile string var latestMetaFileTime time.Time for _, subdir := range subdirs { // 检查子目录是否是目录 if subdir.IsDir() { subdirPath := filepath.Join(directory, subdir.Name()) // 获取子目录下的所有文件 files, err := ioutil.ReadDir(subdirPath) if err != nil { return "", fmt.Errorf("读取子目录失败:%s", err) } for _, file := range files { // 检查文件是否是.meta文件 if !file.IsDir() && filepath.Ext(file.Name()) == ".meta" { // 获取文件的修改时间 modifiedTime := file.ModTime() // 如果找到的文件的修改时间比当前最新的.meta文件的修改时间更晚,则更新最新的.meta文件路径和修改时间 if modifiedTime.After(latestMetaFileTime) { latestMetaFile = filepath.Join(subdirPath, file.Name()) latestMetaFileTime = modifiedTime } } } } } if latestMetaFile == "" { return "", fmt.Errorf("未找到.meta文件") } return latestMetaFile, nil } func (d *GameArchive) Snapshoot(clusterName string) Meta { sessionPath := filepath.Join(d.archive.KleiBasePath(clusterName), clusterName, "Master", "save", "session") p, err := findLatestMetaFile(sessionPath) if err != nil { fmt.Println("查找meta文件失败", err) return Meta{} } content, err := fileUtils.ReadFile(p) if err != nil { fmt.Println("读取meta文件失败", err) return Meta{} } var data Meta err = luaUtils.LuaTable2Struct(content[:len(content)-1], reflect.ValueOf(&data).Elem()) if err != nil { fmt.Println("解析meta文件失败", err) return Meta{} } return data } ================================================ FILE: internal/service/gameConfig/game_config.go ================================================ package gameConfig import ( "dst-admin-go/internal/pkg/utils/collectionUtils" "dst-admin-go/internal/pkg/utils/dstUtils" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/levelConfig" "log" "path/filepath" "strings" "github.com/go-ini/ini" ) const ( ClusterIniTemplate = "./static/template/cluster2.ini" MasterServerIniTemplate = "./static/template/master_server.ini" CavesServerIniTemplate = "./static/template/caves_server.ini" ServerIniTemplate = "./static/template/server.ini" ) type ClusterIni struct { // [GAEMPLAY] GameMode string `json:"game_mode"` MaxPlayers uint `json:"max_players"` Pvp bool `json:"pvp"` PauseWhenNobody bool `json:"pause_when_nobody"` VoteEnabled bool `json:"vote_enabled"` VoteKickEnabled bool `json:"vote_kick_enabled"` // [NETWORK] LanOnlyCluster bool `json:"lan_only_cluster"` ClusterIntention string `json:"cluster_intention"` ClusterDescription string `json:"cluster_description"` ClusterPassword string `json:"cluster_password"` ClusterName string `json:"cluster_name"` OfflineCluster bool `json:"offline_cluster"` ClusterLanguage string `json:"cluster_language"` WhitelistSlots uint `json:"whitelist_slots"` TickRate uint `json:"tick_rate"` // [MISC] ConsoleEnabled bool `json:"console_enabled"` MaxSnapshots uint `json:"max_snapshots"` // [SHARD] ShardEnabled bool `json:"shard_enabled"` BindIp string `json:"bind_ip"` MasterIp string `json:"master_ip"` MasterPort uint `json:"master_port"` ClusterKey string `json:"cluster_key"` // [STEAM] SteamGroupId string `json:"steam_group_id"` SteamGroupOnly bool `json:"steam_group_only"` SteamGroupAdmins bool `json:"steam_group_admins"` } type ServerIni struct { // [NETWORK] ServerPort uint `json:"server_port"` // [SHARD] IsMaster bool `json:"is_master"` Name string `json:"name"` Id uint `json:"id"` // [ACCOUNT] EncodeUserPath bool `json:"encode_user_path"` // [STEAM] AuthenticationPort uint `json:"authentication_port"` MasterServerPort uint `json:"master_server_port"` } type ClusterIniConfig struct { ClusterIni *ClusterIni `json:"cluster"` Token string `json:"token"` } type GameConfig struct { archive *archive.PathResolver levelConfigUtils *levelConfig.LevelConfigUtils } func NewGameConfig(archive *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) *GameConfig { return &GameConfig{ archive: archive, levelConfigUtils: levelConfigUtils, } } func (p *GameConfig) GetClusterIniConfig(clusterName string) (ClusterIniConfig, error) { clusterIni, err := p.GetClusterIni(clusterName) if err != nil { return ClusterIniConfig{}, err } clusterToken, err := p.GetClusterToken(clusterName) if err != nil { return ClusterIniConfig{}, err } return ClusterIniConfig{ ClusterIni: &clusterIni, Token: clusterToken, }, nil } func (p *GameConfig) SaveClusterIniConfig(clusterName string, config *ClusterIniConfig) error { err := p.SaveClusterIni(clusterName, config.ClusterIni) if err != nil { return err } err = p.SaveClusterToken(clusterName, config.Token) if err != nil { return err } return nil } func (p *GameConfig) GetClusterIni(clusterName string) (ClusterIni, error) { // return fileUtils.ReadLnFile(p.archive.ClusterPath(clusterName)) // 加载 INI 文件 clusterIniPath := p.archive.ClusterIniPath(clusterName) if !fileUtils.Exists(clusterIniPath) { err := fileUtils.CreateFileIfNotExists(clusterIniPath) if err != nil { return ClusterIni{}, err } } cfg, err := ini.Load(clusterIniPath) if err != nil { log.Panicln("Failed to load INI file:", err) } // [GAMEPLAY] GAMEPLAY := cfg.Section("GAMEPLAY") newClusterIni := ClusterIni{} newClusterIni.GameMode = GAMEPLAY.Key("game_mode").String() newClusterIni.MaxPlayers = GAMEPLAY.Key("max_players").MustUint(8) newClusterIni.Pvp = GAMEPLAY.Key("pvp").MustBool(false) newClusterIni.PauseWhenNobody = GAMEPLAY.Key("pause_when_empty").MustBool(true) newClusterIni.VoteEnabled = GAMEPLAY.Key("vote_enabled").MustBool(true) newClusterIni.VoteKickEnabled = GAMEPLAY.Key("vote_kick_enabled").MustBool(true) // [NETWORK] NETWORK := cfg.Section("NETWORK") newClusterIni.LanOnlyCluster = NETWORK.Key("lan_only_cluster").MustBool(false) newClusterIni.ClusterIntention = NETWORK.Key("cluster_intention").String() newClusterIni.ClusterPassword = NETWORK.Key("cluster_password").String() newClusterIni.ClusterDescription = NETWORK.Key("cluster_description").String() newClusterIni.ClusterName = NETWORK.Key("cluster_name").String() newClusterIni.OfflineCluster = NETWORK.Key("offline_cluster").MustBool(false) newClusterIni.ClusterLanguage = NETWORK.Key("cluster_language").MustString("zh") newClusterIni.WhitelistSlots = NETWORK.Key("whitelist_slots").MustUint(0) newClusterIni.TickRate = NETWORK.Key("tick_rate").MustUint(15) // [MISC] MISC := cfg.Section("MISC") newClusterIni.ConsoleEnabled = MISC.Key("console_enabled").MustBool(true) newClusterIni.MaxSnapshots = MISC.Key("max_snapshots").MustUint(6) // [SHARD] SHARD := cfg.Section("SHARD") newClusterIni.ShardEnabled = SHARD.Key("shard_enabled").MustBool(true) newClusterIni.BindIp = SHARD.Key("bind_ip").MustString("127.0.0.1") newClusterIni.MasterIp = SHARD.Key("master_ip").MustString("127.0.0.1") newClusterIni.MasterPort = SHARD.Key("master_port").MustUint(10888) newClusterIni.ClusterKey = SHARD.Key("cluster_key").String() // [STEAM] STEAM := cfg.Section("STEAM") newClusterIni.SteamGroupId = STEAM.Key("steam_group_id").MustString("") newClusterIni.SteamGroupOnly = STEAM.Key("steam_group_only").MustBool(false) newClusterIni.SteamGroupAdmins = STEAM.Key("steam_group_admins").MustBool(false) clusterIni, err := fileUtils.ReadLnFile(clusterIniPath) if err != nil { panic("read cluster.ini file error: " + err.Error()) } for _, value := range clusterIni { if value == "" { continue } if strings.Contains(value, "cluster_password") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) newClusterIni.ClusterPassword = s } } if strings.Contains(value, "cluster_description") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) newClusterIni.ClusterDescription = s } } if strings.Contains(value, "cluster_name") { split := strings.Split(value, "=") if len(split) > 1 { s := strings.TrimSpace(split[1]) newClusterIni.ClusterName = s } } } return newClusterIni, nil } func (p *GameConfig) SaveClusterIni(clusterName string, clusterIni *ClusterIni) error { clusterIniPath := p.archive.ClusterIniPath(clusterName) err := fileUtils.WriterTXT(clusterIniPath, dstUtils.ParseTemplate(ClusterIniTemplate, clusterIni)) return err } func (p *GameConfig) GetClusterToken(clusterName string) (string, error) { return fileUtils.ReadFile(p.archive.ClusterTokenPath(clusterName)) } func (p *GameConfig) SaveClusterToken(clusterName string, token string) error { return fileUtils.WriterTXT(p.archive.ClusterTokenPath(clusterName), token) } func (p *GameConfig) GetAdminList(clusterName string) ([]string, error) { return fileUtils.ReadLnFile(p.archive.AdminlistPath(clusterName)) } func (p *GameConfig) GetBlackList(clusterName string) ([]string, error) { return fileUtils.ReadLnFile(p.archive.BlacklistPath(clusterName)) } func (p *GameConfig) GetWhithList(clusterName string) ([]string, error) { return fileUtils.ReadLnFile(p.archive.WhitelistPath(clusterName)) } func (p *GameConfig) SaveAdminList(clusterName string, list []string) error { path := p.archive.AdminlistPath(clusterName) err := fileUtils.CreateFileIfNotExists(path) if err != nil { return err } lnFile, err := fileUtils.ReadLnFile(path) set := collectionUtils.ToSet(append(lnFile, list...)) err = fileUtils.WriterLnFile(path, set) return err } func (p *GameConfig) SaveBlackList(clusterName string, list []string) error { path := p.archive.BlacklistPath(clusterName) err := fileUtils.CreateFileIfNotExists(path) if err != nil { return err } lnFile, err := fileUtils.ReadLnFile(path) set := collectionUtils.ToSet(append(lnFile, list...)) err = fileUtils.WriterLnFile(path, set) return err } func (p *GameConfig) SaveWhithList(clusterName string, list []string) error { path := p.archive.WhitelistPath(clusterName) err := fileUtils.CreateFileIfNotExists(path) if err != nil { return err } lnFile, err := fileUtils.ReadLnFile(path) set := collectionUtils.ToSet(append(lnFile, list...)) err = fileUtils.WriterLnFile(path, set) return err } type HomeConfigVO struct { ClusterIntention string `json:"clusterIntention"` ClusterName string `json:"clusterName"` ClusterDescription string `json:"clusterDescription"` GameMode string `json:"gameMode"` Pvp bool `json:"pvp"` MaxPlayers uint `json:"maxPlayers"` MaxSnapshots uint `json:"max_snapshots"` ClusterPassword string `json:"clusterPassword"` Token string `json:"token"` MasterMapData string `json:"masterMapData"` CavesMapData string `json:"cavesMapData"` ModData string `json:"modData"` Otype int64 `json:"type"` PauseWhenNobody bool `json:"pause_when_nobody"` VoteEnabled bool `json:"vote_enabled"` } func (p *GameConfig) GetHomeConfig(clusterName string) (HomeConfigVO, error) { clusterToken, err := p.GetClusterToken(clusterName) if err != nil { return HomeConfigVO{}, err } clusterIni, err := p.GetClusterIni(clusterName) if err != nil { return HomeConfigVO{}, err } masterData, err := fileUtils.ReadFile(p.archive.DataFilePath(clusterName, "Master", "leveldataoverride.lua")) if err != nil { return HomeConfigVO{}, err } cavesData, err := fileUtils.ReadFile(p.archive.DataFilePath(clusterName, "Caves", "leveldataoverride.lua")) if err != nil { return HomeConfigVO{}, err } modData, err := fileUtils.ReadFile(p.archive.DataFilePath(clusterName, "Master", "modoverrides.lua")) if err != nil { return HomeConfigVO{}, err } homeConfigVo := HomeConfigVO{ ClusterIntention: clusterIni.ClusterIntention, ClusterName: clusterIni.ClusterName, ClusterDescription: clusterIni.ClusterDescription, GameMode: clusterIni.GameMode, Pvp: clusterIni.Pvp, MaxPlayers: clusterIni.MaxPlayers, MaxSnapshots: clusterIni.MaxSnapshots, ClusterPassword: clusterIni.ClusterPassword, Token: clusterToken, PauseWhenNobody: clusterIni.PauseWhenNobody, VoteEnabled: clusterIni.VoteEnabled, MasterMapData: masterData, CavesMapData: cavesData, ModData: modData, } return homeConfigVo, nil } func (p *GameConfig) SaveConfig(clusterName string, homeConfig HomeConfigVO) { modConfig := homeConfig.ModData if modConfig != "" { config, _ := p.levelConfigUtils.GetLevelConfig(clusterName) for i := range config.LevelList { clusterPath := p.archive.ClusterPath(clusterName) fileUtils.WriterTXT(filepath.Join(clusterPath, config.LevelList[i].File, "modoverrides.lua"), modConfig) } var serverModSetup = "" workshopIds := dstUtils.WorkshopIds(modConfig) for _, workshopId := range workshopIds { serverModSetup += "ServerModSetup(\"" + workshopId + "\")\n" } fileUtils.WriterTXT(p.archive.GetModSetup(clusterName), serverModSetup) } } ================================================ FILE: internal/service/level/level.go ================================================ package level import ( "dst-admin-go/internal/pkg/utils/dstUtils" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/dstConfig" "dst-admin-go/internal/service/game" "dst-admin-go/internal/service/gameConfig" "dst-admin-go/internal/service/levelConfig" "log" "path/filepath" "strconv" "time" "github.com/go-ini/ini" ) // LevelService 关卡服务结构体 type LevelService struct { gameProcess game.Process dstConfig dstConfig.Config resolver *archive.PathResolver levelConfigUtils *levelConfig.LevelConfigUtils } // NewLevelService 创建关卡服务实例 func NewLevelService(gameProcess game.Process, dstConfig dstConfig.Config, resolver *archive.PathResolver, levelConfigUtils *levelConfig.LevelConfigUtils) *LevelService { return &LevelService{ gameProcess: gameProcess, dstConfig: dstConfig, resolver: resolver, levelConfigUtils: levelConfigUtils, } } // GetLevelList 获取关卡列表 func (l *LevelService) GetLevelList(clusterName string) []levelConfig.LevelInfo { config, err := l.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { return []levelConfig.LevelInfo{} } var levels []levelConfig.LevelInfo if len(config.LevelList) == 0 { masterLevelPath := filepath.Join(l.resolver.ClusterPath(clusterName), "Master") if !fileUtils.Exists(masterLevelPath) { master := levelConfig.LevelInfo{ IsMaster: true, LevelName: "森林", Uuid: "Master", Leveldataoverride: "return {}", Modoverrides: "return {}", ServerIni: levelConfig.NewMasterServerIni(), } l.initLevel(filepath.Join(l.resolver.ClusterPath(clusterName), "Master"), &master) levels = append([]levelConfig.LevelInfo{}, master) config.LevelList = append(config.LevelList, levelConfig.Item{ Name: "森林", File: "Master", }) err = l.levelConfigUtils.SaveLevelConfig(clusterName, config) if err != nil { log.Println(err) } return levels } else { // 读取现有的 Master 世界配置 master := l.GetLevel(clusterName, "Master") levels = append([]levelConfig.LevelInfo{}, master) config.LevelList = append(config.LevelList, levelConfig.Item{ Name: "森林", File: "Master", }) cavesLevelPath := filepath.Join(l.resolver.ClusterPath(clusterName), "Caves") if fileUtils.Exists(cavesLevelPath) { config.LevelList = append(config.LevelList, levelConfig.Item{ Name: "洞穴", File: "Caves", }) caves := l.GetLevel(clusterName, "Caves") levels = append(levels, caves) } err = l.levelConfigUtils.SaveLevelConfig(clusterName, config) if err != nil { log.Println(err) } return levels } } for i := range config.LevelList { level1 := levelConfig.LevelInfo{} level1.LevelName = config.LevelList[i].Name level1.Uuid = config.LevelList[i].File level1.RunVersion = config.LevelList[i].RunVersion world := l.GetLevel(clusterName, config.LevelList[i].File) level1.Leveldataoverride = world.Leveldataoverride level1.Modoverrides = world.Modoverrides level1.ServerIni = world.ServerIni levels = append(levels, level1) } return levels } // GetLevel 获取单个关卡配置 func (l *LevelService) GetLevel(clusterName string, levelName string) levelConfig.LevelInfo { levelFolderPath := filepath.Join(l.resolver.ClusterPath(clusterName), levelName) config, _ := l.levelConfigUtils.GetLevelConfig(clusterName) name := "" for _, item := range config.LevelList { if item.File == levelName { name = item.Name } } // 读取 leveldataoverride.lua lPath := filepath.Join(levelFolderPath, "leveldataoverride.lua") leveldataoverride, err := fileUtils.ReadFile(lPath) if err != nil { leveldataoverride = "return {}" } // 读取 modoverrides.lua mPath := filepath.Join(levelFolderPath, "modoverrides.lua") modoverrides, err := fileUtils.ReadFile(mPath) if err != nil { modoverrides = "return {}" } // 读取 server.ini sPath := filepath.Join(levelFolderPath, "server.ini") serverIni := l.GetServerIni(sPath, levelName == "Master") return levelConfig.LevelInfo{ IsMaster: levelName == "Master", LevelName: name, Uuid: levelName, Leveldataoverride: leveldataoverride, Modoverrides: modoverrides, ServerIni: serverIni, } } func (l *LevelService) GetServerIni(filepath string, isMaster bool) levelConfig.ServerIni { fileUtils.CreateFileIfNotExists(filepath) var serverPortDefault uint = 10998 idDefault := 10010 if isMaster { serverPortDefault = 10999 idDefault = 10000 } serverIni := levelConfig.NewCavesServerIni() // 加载 INI 文件 cfg, err := ini.Load(filepath) if err != nil { return serverIni } // [NETWORK] NETWORK := cfg.Section("NETWORK") serverIni.ServerPort = NETWORK.Key("server_port").MustUint(serverPortDefault) // [SHARD] SHARD := cfg.Section("SHARD") serverIni.IsMaster = SHARD.Key("is_master").MustBool(isMaster) serverIni.Name = SHARD.Key("name").String() serverIni.Id = SHARD.Key("id").MustUint(uint(idDefault)) // [ACCOUNT] ACCOUNT := cfg.Section("ACCOUNT") serverIni.EncodeUserPath = ACCOUNT.Key("encode_user_path").MustBool(true) // [STEAM] STEAM := cfg.Section("STEAM") serverIni.AuthenticationPort = STEAM.Key("authentication_port").MustUint(8766) serverIni.MasterServerPort = STEAM.Key("master_server_port").MustUint(27016) return serverIni } // UpdateLevels 更新多个关卡配置 func (l *LevelService) UpdateLevels(clusterName string, levels []levelConfig.LevelInfo) error { for i := range levels { config, _ := l.dstConfig.GetDstConfig(clusterName) dstUtils.DedicatedServerModsSetup(config, levels[i].Modoverrides) err := l.UpdateLevel(clusterName, &levels[i]) if err != nil { return err } } return nil } // UpdateLevel 更新单个关卡配置 func (l *LevelService) UpdateLevel(clusterName string, level *levelConfig.LevelInfo) error { levelFolderPath := filepath.Join(l.resolver.ClusterPath(clusterName), level.Uuid) fileUtils.CreateDirIfNotExists(levelFolderPath) l.initLevel(levelFolderPath, level) // 记录level.json 文件 levelConfig, err := l.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { return err } for i := range levelConfig.LevelList { if level.Uuid == levelConfig.LevelList[i].File { levelConfig.LevelList[i].Name = level.LevelName // 更新世界配置 l.initLevel(levelFolderPath, level) break } } err = l.levelConfigUtils.SaveLevelConfig(clusterName, levelConfig) return err } // CreateLevel 创建新关卡 func (l *LevelService) CreateLevel(clusterName string, level *levelConfig.LevelInfo) error { uuid := "" if level.Uuid == "" { uuid = l.generateUUID() } else { uuid = level.Uuid } levelFolderPath := filepath.Join(l.resolver.ClusterPath(clusterName), uuid) fileUtils.CreateDirIfNotExists(levelFolderPath) l.initLevel(levelFolderPath, level) // 记录level.json 文件 config, err := l.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { return err } config.LevelList = append(config.LevelList, levelConfig.Item{Name: level.LevelName, File: uuid}) err = l.levelConfigUtils.SaveLevelConfig(clusterName, config) if err != nil { err := fileUtils.DeleteFile(filepath.Join(l.resolver.ClusterPath(clusterName), uuid)) return err } level.Uuid = uuid return nil } // DeleteLevel 删除关卡 func (l *LevelService) DeleteLevel(clusterName string, levelName string) error { // 停止关卡服务 l.gameProcess.Stop(clusterName, levelName) // 删除关卡目录 err := fileUtils.DeleteDir(filepath.Join(l.resolver.ClusterPath(clusterName), levelName)) if err != nil { return err } // 删除 json 文件中的记录 config, err := l.levelConfigUtils.GetLevelConfig(clusterName) if err != nil { log.Panicln("删除文件失败") } newLevelsConfig := levelConfig.LevelConfig{} for i := range config.LevelList { if config.LevelList[i].File != levelName { newLevelsConfig.LevelList = append(newLevelsConfig.LevelList, config.LevelList[i]) } } err = l.levelConfigUtils.SaveLevelConfig(clusterName, &newLevelsConfig) // TODO 同时删除定时任务和自动维护 return err } // initLevel 初始化关卡文件 func (l *LevelService) initLevel(levelFolderPath string, level *levelConfig.LevelInfo) { lPath := filepath.Join(levelFolderPath, "leveldataoverride.lua") mPath := filepath.Join(levelFolderPath, "modoverrides.lua") sPath := filepath.Join(levelFolderPath, "server.ini") fileUtils.CreateFileIfNotExists(lPath) fileUtils.CreateFileIfNotExists(mPath) fileUtils.CreateFileIfNotExists(sPath) fileUtils.WriterTXT(lPath, level.Leveldataoverride) fileUtils.WriterTXT(mPath, level.Modoverrides) serverBuf := l.ParseTemplate(level.ServerIni) fileUtils.WriterTXT(sPath, serverBuf) } // ParseTemplate 解析服务器配置模板 func (l *LevelService) ParseTemplate(serverIni levelConfig.ServerIni) string { // 使用 gameConfig 中的 ParseTemplate 方法 return dstUtils.ParseTemplate(gameConfig.ServerIniTemplate, serverIni) } // generateUUID 生成 UUID func (l *LevelService) generateUUID() string { // 简化实现,实际应该使用标准的 UUID 生成库 return "level_" + strconv.FormatInt(time.Now().UnixNano(), 10) } ================================================ FILE: internal/service/levelConfig/level_config.go ================================================ package levelConfig import ( "dst-admin-go/internal/pkg/utils/dstUtils" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/archive" "encoding/json" "log" "os" "path/filepath" ) type Item struct { Name string `json:"name"` File string `json:"file"` RunVersion int64 `json:"runVersion"` Version int64 `json:"Version"` } type LevelConfig struct { LevelList []Item `json:"levelList"` } // LevelInfo 世界配置结构体 type LevelInfo struct { IsMaster bool `json:"isMaster"` LevelName string `json:"levelName"` Uuid string `json:"uuid"` RunVersion int64 `json:"runVersion"` Leveldataoverride string `json:"leveldataoverride"` Modoverrides string `json:"modoverrides"` ServerIni ServerIni `json:"server_ini"` } type ServerIni struct { // [NETWORK] ServerPort uint `json:"server_port"` // [SHARD] IsMaster bool `json:"is_master"` Name string `json:"name"` Id uint `json:"id"` // [ACCOUNT] EncodeUserPath bool `json:"encode_user_path"` // [STEAM] AuthenticationPort uint `json:"authentication_port"` MasterServerPort uint `json:"master_server_port"` } func NewMasterServerIni() ServerIni { return ServerIni{ ServerPort: 10999, IsMaster: true, Name: "Master", Id: 10000, EncodeUserPath: true, } } func NewCavesServerIni() ServerIni { return ServerIni{ ServerPort: 10998, IsMaster: false, Name: "Caves", Id: 10010, EncodeUserPath: true, AuthenticationPort: 8766, MasterServerPort: 27016, } } type LevelConfigUtils struct { archive *archive.PathResolver } func NewLevelConfigUtils(archive *archive.PathResolver) *LevelConfigUtils { return &LevelConfigUtils{ archive: archive, } } func (p *LevelConfigUtils) initLevel(levelFolderPath string, level *LevelInfo) { lPath := filepath.Join(levelFolderPath, "leveldataoverride.lua") mPath := filepath.Join(levelFolderPath, "modoverrides.lua") sPath := filepath.Join(levelFolderPath, "server.ini") fileUtils.CreateFileIfNotExists(lPath) fileUtils.CreateFileIfNotExists(mPath) fileUtils.CreateFileIfNotExists(sPath) fileUtils.WriterTXT(lPath, level.Leveldataoverride) fileUtils.WriterTXT(mPath, level.Modoverrides) serverBuf := dstUtils.ParseTemplate("./static/template/server.ini", level.ServerIni) fileUtils.WriterTXT(sPath, serverBuf) } func (p *LevelConfigUtils) GetLevelConfig(clusterName string) (*LevelConfig, error) { clusterBasePath := p.archive.ClusterPath(clusterName) jsonPath := filepath.Join(clusterBasePath, "level.json") fileUtils.CreateDirIfNotExists(clusterBasePath) // fileUtils.CreateFileIfNotExists(jsonPath) if !fileUtils.Exists(jsonPath) { fileUtils.CreateFile(jsonPath) fileUtils.WriterTXT(jsonPath, "{}") } // 打开JSON文件 file, err := os.Open(jsonPath) if err != nil { log.Println("无法打开level.json文件:", err) return nil, err } defer file.Close() // 解码JSON数据 var config LevelConfig decoder := json.NewDecoder(file) err = decoder.Decode(&config) if err != nil { log.Println("无法解析level.json文件:", err) return nil, err } if len(config.LevelList) == 0 { masterLevelPath := filepath.Join(clusterBasePath, "Master") if !fileUtils.Exists(masterLevelPath) { master := LevelInfo{ IsMaster: true, LevelName: "森林", Uuid: "Master", Leveldataoverride: "return {}", Modoverrides: "return {}", ServerIni: NewMasterServerIni(), } p.initLevel(filepath.Join(clusterBasePath, "Master"), &master) config.LevelList = append(config.LevelList, Item{ Name: "森林", File: "Master", }) err = p.SaveLevelConfig(clusterName, &config) if err != nil { log.Println(err) } } else { config.LevelList = append(config.LevelList, Item{ Name: "森林", File: "Master", }) cavesLevelPath := filepath.Join(clusterBasePath, "Caves") if fileUtils.Exists(cavesLevelPath) { config.LevelList = append(config.LevelList, Item{ Name: "洞穴", File: "Caves", }) } err = p.SaveLevelConfig(clusterName, &config) if err != nil { log.Println(err) } } } return &config, nil } func (p *LevelConfigUtils) SaveLevelConfig(clusterName string, levelConfig *LevelConfig) error { clusterBasePath := p.archive.ClusterPath(clusterName) jsonPath := filepath.Join(clusterBasePath, "level.json") fileUtils.CreateFileIfNotExists(jsonPath) // 打开JSON文件 file, err := os.Open(jsonPath) if err != nil { log.Println("无法打开level.json文件:", err) return err } defer file.Close() bytes, err := json.Marshal(levelConfig) if err != nil { log.Println("json 解析错误") } fileUtils.WriterTXT(jsonPath, string(bytes)) return err } ================================================ FILE: internal/service/login/login_service.go ================================================ package login import ( "dst-admin-go/internal/config" "dst-admin-go/internal/pkg/response" "dst-admin-go/internal/pkg/utils/fileUtils" "fmt" "log" "net" "strings" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" ) const ( PasswordPath = "./password.txt" ) type LoginService struct { config *config.Config } type UserInfo struct { Username string `json:"username"` Password string `json:"password"` DisplayName string `json:"displayName"` PhotoURL string `json:"photoURL"` } func NewLoginService(config *config.Config) *LoginService { return &LoginService{ config: config, } } func (l *LoginService) GetUserInfo() UserInfo { user, err := fileUtils.ReadLnFile(PasswordPath) if err != nil { log.Panicln("Not find password file error: " + err.Error()) } username := strings.TrimSpace(strings.Split(user[0], "=")[1]) // password := strings.TrimSpace(strings.Split(user[1], "=")[1]) displayName := strings.TrimSpace(strings.Split(user[2], "=")[1]) photoURL := strings.TrimSpace(strings.Split(user[3], "=")[1]) return UserInfo{ Username: username, DisplayName: displayName, PhotoURL: photoURL, } } func (l *LoginService) Login(userInfo UserInfo, ctx *gin.Context) *response.Response { response := &response.Response{} user, err := fileUtils.ReadLnFile(PasswordPath) if err != nil { log.Panicln("Not find password file error: " + err.Error()) } username := strings.TrimSpace(strings.Split(user[0], "=")[1]) password := strings.TrimSpace(strings.Split(user[1], "=")[1]) displayName := strings.TrimSpace(strings.Split(user[2], "=")[1]) photoURL := strings.TrimSpace(strings.Split(user[3], "=")[1]) white := l.IsWhiteIP(ctx) if !white { if username != userInfo.Username || password != userInfo.Password { log.Panicln("User authentication failed") response.Code = 401 response.Msg = "User authentication failed" return response } } session := sessions.Default(ctx) session.Set("username", username) err = session.Save() if err != nil { log.Panicln(err) } response.Code = 200 response.Msg = "Login success" response.Data = map[string]interface{}{ "username": username, "displayName": displayName, "photoURL": photoURL, } return response } func (l *LoginService) Logout(ctx *gin.Context) { session := sessions.Default(ctx) session.Clear() err := session.Save() if err != nil { log.Panicln(err) } } func (l *LoginService) DirectLogin(ctx *gin.Context) { user, err := fileUtils.ReadLnFile(PasswordPath) if err != nil { log.Panicln("Not find password file error: " + err.Error()) } username := strings.TrimSpace(strings.Split(user[0], "=")[1]) session := sessions.Default(ctx) session.Set("username", username) } func (l *LoginService) ChangeUser(username, password string) { user, err := fileUtils.ReadLnFile(PasswordPath) if err != nil { log.Panicln("Not find password file error: " + err.Error()) } displayName := strings.TrimSpace(strings.Split(user[2], "=")[1]) photoURL := strings.TrimSpace(strings.Split(user[3], "=")[1]) fileUtils.WriterLnFile(PasswordPath, []string{ "username = " + username, "password = " + password, "displayName=" + displayName, "photoURL=" + photoURL, }) } func (l *LoginService) ChangePassword(newPassword string) *response.Response { response := &response.Response{} user, err := fileUtils.ReadLnFile(PasswordPath) if err != nil { log.Panicln("Not find password file error: " + err.Error()) } username := strings.TrimSpace(strings.Split(user[0], "=")[1]) displayName := strings.TrimSpace(strings.Split(user[2], "=")[1]) photoURL := strings.TrimSpace(strings.Split(user[3], "=")[1]) fileUtils.WriterLnFile(PasswordPath, []string{ "username = " + username, "password = " + newPassword, "displayName=" + displayName, "photoURL=" + photoURL, }) response.Code = 200 response.Msg = "Update user new password success" return response } func (l *LoginService) InitUserInfo(userInfo UserInfo) { username := "username=" + userInfo.Username password := "password=" + userInfo.Password displayName := "displayName=" + userInfo.DisplayName photoURL := "photoURL=" + userInfo.PhotoURL fileUtils.WriterLnFile(PasswordPath, []string{username, password, displayName, photoURL}) } func (l *LoginService) IsWhiteIP(ctx *gin.Context) bool { if l.config == nil { return false } WhiteAdminIP := l.config.WhiteAdminIP if WhiteAdminIP != "" { // ipaddr := ctx.Request.RemoteAddr ip, _, _ := net.SplitHostPort(ipaddr) if ip != "" { ipnet := net.ParseIP(ip) adminips := strings.Split(WhiteAdminIP, ",") //fmt.Println(ipnet) for _, s := range adminips { if strings.Count(s, "/") > 0 { _, netadmin, err := net.ParseCIDR(s) //fmt.Println(netadmin) //fmt.Println(len) if err != nil { fmt.Printf("Error parsing CIDR: %v\n", err) } if netadmin.Contains(ipnet) { return true } } else { netadmin := net.ParseIP(s) if netadmin != nil && netadmin.Equal(ipnet) { return true } } } } } return false } ================================================ FILE: internal/service/mod/mod_service.go ================================================ package mod import ( "archive/zip" "bytes" "crypto/tls" "dst-admin-go/internal/model" "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/pkg/utils/shellUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/dstConfig" "encoding/json" "errors" "fmt" "io" "io/ioutil" "log" "math" "mime/multipart" "net/http" "net/url" "os" "os/exec" "path/filepath" "regexp" "runtime" "strconv" "strings" "sync" "time" lua "github.com/yuin/gopher-lua" "gorm.io/gorm" ) const ( steamAPIKey = "73DF9F781D195DFD3D19DED1CB72EEE6" appID = 322330 language = 6 ) type ModService struct { db *gorm.DB dstConfig dstConfig.Config pathResolver *archive.PathResolver } func NewModService(db *gorm.DB, config dstConfig.Config, pathResolver *archive.PathResolver) *ModService { return &ModService{ db: db, dstConfig: config, pathResolver: pathResolver, } } // SearchResult 搜索结果 type SearchResult struct { Page int `json:"page"` Size int `json:"size"` Total int `json:"total"` TotalPage int `json:"totalPage"` Data []ModInfo `json:"data"` } // ModInfo 搜索返回的mod信息 type ModInfo struct { ID string `json:"id"` Name string `json:"name"` Author string `json:"author"` Desc string `json:"desc"` Time int `json:"time"` Sub int `json:"sub"` Img string `json:"img"` FileUrl string `json:"file_url"` V string `json:"v"` LastTime float64 `json:"last_time"` ConsumerAppid float64 `json:"consumer_appid"` CreatorAppid float64 `json:"creator_appid"` Vote struct { Star int `json:"star"` Num int `json:"num"` } `json:"vote"` Child []string `json:"child,omitempty"` } // Publishedfiledetail Steam API 返回的模组详情 type Publishedfiledetail struct { Publishedfileid string `json:"publishedfileid"` Result int `json:"result"` Creator string `json:"creator"` CreatorAppID int `json:"creator_app_id"` ConsumerAppID int `json:"consumer_app_id"` Filename string `json:"filename"` FileURL string `json:"file_url"` HcontentFile string `json:"hcontent_file"` PreviewURL string `json:"preview_url"` HcontentPreview string `json:"hcontent_preview"` Title string `json:"title"` Description string `json:"description"` TimeCreated float64 `json:"time_created"` TimeUpdated float64 `json:"time_updated"` Visibility int `json:"visibility"` BanReason string `json:"ban_reason"` Subscriptions int `json:"subscriptions"` Favorited int `json:"favorited"` LifetimeSubscriptions int `json:"lifetime_subscriptions"` LifetimeFavorited int `json:"lifetime_favorited"` Views int `json:"views"` Tags []struct { Tag string `json:"tag"` } `json:"tags"` } // WorkshopItemDetail UGC mod详情 type WorkshopItemDetail struct { WorkShopId string `json:"workshopId"` Name string `json:"name"` Timeupdated int64 `json:"timeupdated"` Timelast float64 `json:"timelast"` Img string `json:"img"` } // WorkshopItem ACF文件中的Workshop项 type WorkshopItem struct { TimeUpdated int64 Manifest string Ugchandle string } // SearchModList 搜索模组列表 func (s *ModService) SearchModList(text string, page, size int, lang string) (*SearchResult, error) { // 判断是否是modID搜索 modId, ok := isModId(text) if ok { modInfo := s.searchModInfoByWorkshopId(modId) data := []ModInfo{} if modInfo.ID != "" { data = append(data, modInfo) } return &SearchResult{ Page: 1, Size: 1, Total: 1, TotalPage: 1, Data: data, }, nil } // 调用 Steam API 搜索 urlStr := "http://api.steampowered.com/IPublishedFileService/QueryFiles/v1/" data := url.Values{ "page": {fmt.Sprintf("%d", page)}, "key": {steamAPIKey}, "appid": {"322330"}, "language": {"6"}, "return_tags": {"true"}, "numperpage": {fmt.Sprintf("%d", size)}, "search_text": {text}, "return_vote_data": {"true"}, "return_children": {"true"}, } if lang == "zh" { data.Set("language", "6") } else { data.Set("language", "") } urlStr = urlStr + "?" + data.Encode() var modData map[string]interface{} for i := 0; i < 2; i++ { resp, err := http.Get(urlStr) if err != nil { return nil, fmt.Errorf("搜索mod失败: %w", err) } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(&modData) if err != nil { return nil, fmt.Errorf("解析mod数据失败: %w", err) } if modData["response"] != nil { break } } if modData["response"] == nil { return nil, errors.New("no response found in mod data") } modResponse := modData["response"].(map[string]interface{}) total := int(modResponse["total"].(float64)) modInfoRaw := modResponse["publishedfiledetails"].([]interface{}) modList := make([]ModInfo, 0) if len(modInfoRaw) > 0 { for _, modInfoRaw := range modInfoRaw { modInfo := modInfoRaw.(map[string]interface{}) img := modInfo["preview_url"].(string) voteData := modInfo["vote_data"].(map[string]interface{}) auth := modInfo["creator"].(string) var authorURL string if auth != "" { authorURL = fmt.Sprintf("https://steamcommunity.com/profiles/%s/?xml=1", auth) } mod := ModInfo{ ID: fmt.Sprintf("%v", modInfo["publishedfileid"]), Name: fmt.Sprintf("%v", modInfo["title"]), Author: authorURL, Desc: fmt.Sprintf("%v", modInfo["file_description"]), Time: int(modInfo["time_updated"].(float64)), Sub: int(modInfo["subscriptions"].(float64)), Img: img, Vote: struct { Star int `json:"star"` Num int `json:"num"` }{ Star: int(voteData["score"].(float64)*5) + 1, Num: int(voteData["votes_up"].(float64) + voteData["votes_down"].(float64)), }, } if modInfo["num_children"].(float64) != 0 { children := modInfo["children"].([]interface{}) child := make([]string, len(children)) for i, c := range children { child[i] = fmt.Sprintf("%v", c.(map[string]interface{})["publishedfileid"]) } mod.Child = child } modList = append(modList, mod) } } return &SearchResult{ Page: page, Size: size, Total: total, TotalPage: int(math.Ceil(float64(total) / float64(size))), Data: modList, }, nil } // SubscribeModByModId 订阅并下载模组 func (s *ModService) SubscribeModByModId(clusterName, modId, lang string) (*model.ModInfo, error) { if !isWorkshopId(modId) { // 非workshop mod,从本地读取 return s.getLocalModInfo(clusterName, lang, modId) } // 从Steam API获取mod信息 urlStr := "http://api.steampowered.com/IPublishedFileService/GetDetails/v1/" data := url.Values{} data.Set("key", steamAPIKey) data.Set("language", "6") data.Set("publishedfileids[0]", modId) urlStr = urlStr + "?" + data.Encode() req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, fmt.Errorf("创建请求失败: %w", err) } client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("请求Steam API失败: %w", err) } defer resp.Body.Close() var result map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return nil, fmt.Errorf("解析响应失败: %w", err) } dataList, ok := result["response"].(map[string]interface{})["publishedfiledetails"].([]interface{}) if !ok || len(dataList) == 0 { return nil, errors.New("获取mod信息失败") } data2 := dataList[0].(map[string]interface{}) img := data2["preview_url"].(string) auth := data2["creator"].(string) var authorURL string if auth != "" { authorURL = fmt.Sprintf("https://steamcommunity.com/profiles/%s/?xml=1", auth) } name := data2["title"].(string) lastTime := data2["time_updated"].(float64) description := data2["file_description"].(string) auth = authorURL fileUrl := data2["file_url"] img = fmt.Sprintf("%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true", img) v := s.getVersion(data2["tags"]) creatorAppid := data2["creator_appid"].(float64) consumerAppid := data2["consumer_appid"].(float64) // 检查数据库中是否已存在 existingMod, err := s.GetModByModId(modId) if err == nil && existingMod.Modid != "" { if lastTime == existingMod.LastTime { return existingMod, nil } // 需要更新 var modConfig string var fileUrlStr = "" if fileUrl != nil { fileUrlStr = fileUrl.(string) } if fileUrlStr != "" { modConfigJson, _ := json.Marshal(s.getV1ModInfoConfig(clusterName, lang, modId, fileUrlStr)) modConfig = string(modConfigJson) } else { modConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modId)) modConfig = string(modConfigJson) } existingMod.LastTime = lastTime existingMod.Name = name existingMod.Auth = auth existingMod.Description = description existingMod.Img = img existingMod.V = v existingMod.ModConfig = modConfig existingMod.Update = false s.db.Save(existingMod) return existingMod, nil } // 新增mod var fileUrlStr = "" if fileUrl != nil { fileUrlStr = fileUrl.(string) } var modConfig string if fileUrlStr != "" { modConfigJson, _ := json.Marshal(s.getV1ModInfoConfig(clusterName, lang, modId, fileUrlStr)) modConfig = string(modConfigJson) } else { modConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modId)) modConfig = string(modConfigJson) } newModInfo := &model.ModInfo{ Auth: auth, ConsumerAppid: consumerAppid, CreatorAppid: creatorAppid, Description: description, FileUrl: fileUrlStr, Modid: modId, Img: img, LastTime: lastTime, Name: name, V: v, ModConfig: modConfig, } err = s.db.Create(newModInfo).Error return newModInfo, err } // GetMyModList 获取已订阅的模组列表 func (s *ModService) GetMyModList() ([]model.ModInfo, error) { var modInfos []model.ModInfo err := s.db.Find(&modInfos).Error return modInfos, err } // GetModByModId 根据modId获取模组 func (s *ModService) GetModByModId(modId string) (*model.ModInfo, error) { var modInfo model.ModInfo err := s.db.Where("modid = ?", modId).First(&modInfo).Error return &modInfo, err } // DeleteMod 删除模组 func (s *ModService) DeleteMod(clusterName, modId string) error { // 从数据库删除 err := s.db.Where("modid = ?", modId).Delete(&model.ModInfo{}).Error if err != nil { return err } // 删除本地文件 config, _ := s.dstConfig.GetDstConfig(clusterName) modDownloadPath := config.Mod_download_path modPath := filepath.Join(modDownloadPath, "steamapps", "workshop", "content", "322330", modId) return fileUtils.DeleteDir(modPath) } // UpdateAllModInfos 批量更新所有模组信息 func (s *ModService) UpdateAllModInfos(clusterName, lang string) error { var modInfos []model.ModInfo var needUpdateList []model.ModInfo var workshopIds []string s.db.Find(&modInfos) for i := range modInfos { workshopIds = append(workshopIds, modInfos[i].Modid) } publishedFileDetails, err := s.getPublishedFileDetailsBatched(workshopIds, 20) if err != nil { return err } for i := range publishedFileDetails { publishedfiledetail := publishedFileDetails[i] for j := range modInfos { if modInfos[j].Modid == publishedfiledetail.Publishedfileid && modInfos[j].LastTime < publishedfiledetail.TimeUpdated { needUpdateList = append(needUpdateList, modInfos[i]) } } } var wg sync.WaitGroup wg.Add(len(needUpdateList)) for i := range needUpdateList { go func(i int) { defer func() { if r := recover(); r != nil { log.Println(r) } wg.Done() }() modId := needUpdateList[i].Modid // 删除之前的数据 config, _ := s.dstConfig.GetDstConfig(clusterName) modDownloadPath := config.Mod_download_path modPath := filepath.Join(modDownloadPath, "/steamapps/workshop/content/322330/", modId) _ = fileUtils.DeleteDir(modPath) _, _ = s.SubscribeModByModId(clusterName, modId, lang) }(i) } wg.Wait() return nil } // DeleteSetupWorkshop 删除所有workshop模组 func (s *ModService) DeleteSetupWorkshop(clusterName string) error { config, err := s.dstConfig.GetDstConfig(clusterName) if err != nil { return err } dstPath := config.Force_install_dir modsPath := filepath.Join(dstPath, "mods") directories, err := fileUtils.ListDirectories(modsPath) if err != nil { return fmt.Errorf("列出目录失败: %w", err) } var workshopList []string for _, directory := range directories { if strings.Contains(directory, "workshop") { workshopList = append(workshopList, directory) } } for _, workshop := range workshopList { err := fileUtils.DeleteDir(workshop) if err != nil { return err } } return nil } // SaveModInfo 保存模组信息 func (s *ModService) SaveModInfo(modInfo *model.ModInfo) error { return s.db.Save(modInfo).Error } // AddModInfo 手动添加模组 func (s *ModService) AddModInfo(clusterName, lang, modid, modinfo, modDownloadPath string) error { // 创建workshop文件 workshopDirPath := filepath.Join(modDownloadPath, "/steamapps/workshop/content/322330", modid) fileUtils.CreateDirIfNotExists(workshopDirPath) modinfoPath := filepath.Join(workshopDirPath, "modinfo.lua") err := fileUtils.CreateFileIfNotExists(modinfoPath) if err != nil { return fmt.Errorf("创建modinfo.lua失败: %w", err) } err = fileUtils.WriterTXT(modinfoPath, modinfo) if err != nil { return fmt.Errorf("写入modinfo.lua失败: %w", err) } // 添加到数据库 return s.addModInfoToDb(clusterName, lang, modid) } // GetUgcModInfo 获取UGC模组信息 func (s *ModService) GetUgcModInfo(clusterName, levelName string) ([]WorkshopItemDetail, error) { acfPath := s.pathResolver.GetUgcAcfPath(clusterName, levelName) acfWorkshops := s.parseACFFile(acfPath) var workshopItemDetails []WorkshopItemDetail var modIds []string for key := range acfWorkshops { modIds = append(modIds, key) } urlStr := "http://api.steampowered.com/IPublishedFileService/GetDetails/v1/" data := url.Values{} data.Set("key", steamAPIKey) data.Set("language", "6") for i := range modIds { data.Set("publishedfileids["+strconv.Itoa(i)+"]", modIds[i]) } urlStr = urlStr + "?" + data.Encode() req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, err } client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var result map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return nil, err } dataList, ok := result["response"].(map[string]interface{})["publishedfiledetails"].([]interface{}) if !ok { return nil, errors.New("解析响应失败") } for i := range dataList { workshop := dataList[i].(map[string]interface{}) _, find := workshop["time_updated"] if find { timeUpdated := workshop["time_updated"].(float64) modId := workshop["publishedfileid"].(string) value, ok := acfWorkshops[modId] if ok { img := workshop["preview_url"].(string) img = fmt.Sprintf("%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true", img) workshopItemDetails = append(workshopItemDetails, WorkshopItemDetail{ WorkShopId: modId, Timeupdated: value.TimeUpdated, Timelast: timeUpdated, Img: img, Name: workshop["title"].(string), }) } } } return workshopItemDetails, nil } // DeleteUgcModFile 删除UGC模组文件 func (s *ModService) DeleteUgcModFile(clusterName, levelName, workshopId string) error { modFilePath := s.pathResolver.GetUgcWorkshopModPath(clusterName, levelName, workshopId) if fileUtils.Exists(modFilePath) { return fileUtils.DeleteDir(modFilePath) } return nil } // ===== 私有方法 ===== // parseACFFile 解析ACF文件 func (s *ModService) parseACFFile(filePath string) map[string]WorkshopItem { lines, err := fileUtils.ReadLnFile(filePath) if err != nil { log.Println(err) return nil } parsingWorkshopItemsInstalled := false workshopItems := make(map[string]WorkshopItem) var currentItemID string var currentItem WorkshopItem for _, line := range lines { if strings.Contains(line, "WorkshopItemsInstalled") { parsingWorkshopItemsInstalled = true continue } if strings.Contains(line, "{") && parsingWorkshopItemsInstalled { continue } if strings.Contains(line, "}") { continue } if parsingWorkshopItemsInstalled { replace := strings.Replace(line, "\t\t", "", -1) replace = strings.Replace(replace, "\"", "", -1) if _, err := strconv.Atoi(replace); err == nil { // This line contains the Workshop Item ID fields := strings.Fields(line) value := strings.Replace(fields[0], "\"", "", -1) currentItemID = value } else { // This line contains the Workshop Item details fields := strings.Fields(line) if len(fields) == 2 { key := strings.Replace(fields[0], "\"", "", -1) value := strings.Replace(fields[1], "\"", "", -1) // Remove double quotes from keys key = strings.ReplaceAll(key, "\"", "") switch key { case "timeupdated": currentItem.TimeUpdated, _ = strconv.ParseInt(value, 10, 64) case "manifest": currentItem.Manifest = strings.ReplaceAll(value, "\"", "") case "ugchandle": currentItem.Ugchandle = strings.ReplaceAll(value, "\"", "") } } } if currentItemID != "" && currentItem.TimeUpdated != 0 { workshopItems[currentItemID] = currentItem currentItemID = "" currentItem = WorkshopItem{} } } } return workshopItems } // getModInfoConfig 获取mod配置信息 func (s *ModService) getModInfoConfig(clusterName, lang, modId string) map[string]interface{} { // 从服务器本地读取mod信息 if dstModInstalledPath, ok := s.getDstUcgsModsInstalledPath(clusterName, modId); ok { modinfoPath := filepath.Join(dstModInstalledPath, "modinfo.lua") if _, err := os.Stat(modinfoPath); err == nil { return s.readModInfo(lang, modId, modinfoPath) } } // 检查mod文件是否已经存在 config, _ := s.dstConfig.GetDstConfig(clusterName) modDownloadPath := config.Mod_download_path fileUtils.CreateDirIfNotExists(modDownloadPath) // 下载的模组位置 modPath := filepath.Join(modDownloadPath, "steamapps", "workshop", "content", "322330", modId) if _, err := os.Stat(modPath); err == nil { log.Println("Mod already downloaded to:", modPath) } else { // 调用 SteamCMD 命令下载 mod steamcmd := config.Steamcmd if runtime.GOOS == "windows" { cmd := "cd /d " + steamcmd + " && Start steamcmd.exe +login anonymous +force_install_dir " + modDownloadPath + " +workshop_download_item 322330 " + modId + " +quit" log.Println("正在下载模组 command:", cmd) _, err := shellUtils.ExecuteCommandInWin(cmd) if err != nil { log.Println("下载mod失败,请检查steamcmd路径是否配置正确", err) return make(map[string]interface{}) } } else { var cmd *exec.Cmd if fileUtils.Exists(filepath.Join(steamcmd, "steamcmd")) { cmd = exec.Command(filepath.Join(steamcmd, "steamcmd"), "+login anonymous", "+force_install_dir", modDownloadPath, "+workshop_download_item 322330 "+modId, "+quit") } else { cmd = exec.Command(filepath.Join(steamcmd, "steamcmd.sh"), "+login anonymous", "+force_install_dir", modDownloadPath, "+workshop_download_item 322330 "+modId, "+quit") } log.Println("正在下载模组 command:", cmd) output, err := cmd.CombinedOutput() if err != nil { log.Println("下载mod失败,请检查steamcmd路径是否配置正确", err) return make(map[string]interface{}) } // 解析 SteamCMD 输出 re := regexp.MustCompile(`Downloaded item \d+ to "([^"]+)"`) match := re.FindStringSubmatch(string(output)) if len(match) < 2 { log.Println("Error parsing output:", string(output)) return make(map[string]interface{}) } log.Println("Mod downloaded to:", match[1]) } } // 查找 modinfo.lua 文件 modinfoPath := filepath.Join(modPath, "modinfo.lua") if _, err := os.Stat(modinfoPath); err != nil { log.Println("Error finding modinfo.lua:", err) return make(map[string]interface{}) } return s.readModInfo(lang, modId, modinfoPath) } // getV1ModInfoConfig 从v1 mod中获取配置 func (s *ModService) getV1ModInfoConfig(clusterName, lang, modid, fileUrl string) map[string]interface{} { log.Println("开始下载 v1 mod,并提取 modinfo.lua 文件") modinfo := map[string][]byte{"modinfo": nil, "modinfo_chs": nil} var tmp bytes.Buffer for i := 0; i < 3; i++ { req, err := http.NewRequest("GET", fileUrl, nil) if err != nil { log.Println(fileUrl, "下载失败", err) continue } client := http.Client{ Timeout: time.Duration(10 * time.Second), } res, err := client.Do(req) if err != nil { log.Println(fileUrl, "下载失败", err) continue } defer res.Body.Close() _, err = tmp.ReadFrom(res.Body) if err != nil { log.Println(err) continue } break } if tmp.Len() == 0 { log.Println(fileUrl, "下载失败 3 次,不再尝试") return make(map[string]interface{}) } log.Println(fileUrl, "下载成功,开始解压") zipReader, err := zip.NewReader(bytes.NewReader(tmp.Bytes()), int64(tmp.Len())) if err != nil { log.Println("模组zip解压失败", err) return make(map[string]interface{}) } _ = s.unzipToDir(zipReader, filepath.Join(s.pathResolver.GetUgcModPath(clusterName), "content", "322330", modid)) for _, file := range zipReader.File { switch file.Name { case "modinfo.lua": f, _ := file.Open() modinfoBytes, err := ioutil.ReadAll(f) if err != nil { log.Println(fileUrl, "解压 modinfo.lua 失败", err) continue } modinfo["modinfo"] = modinfoBytes case "modinfo_chs.lua": f, _ := file.Open() modinfoBytes, err := ioutil.ReadAll(f) if err != nil { log.Println(fileUrl, "解压 modinfo_chs.lua 失败", err) continue } modinfo["modinfo_chs"] = modinfoBytes } } if modinfo["modinfo"] != nil { return s.parseModInfoLua(lang, modid, string(modinfo["modinfo"])) } return make(map[string]interface{}) } // getDstUcgsModsInstalledPath 获取饥荒本身modid的位置 func (s *ModService) getDstUcgsModsInstalledPath(clusterName, modid string) (string, bool) { config, _ := s.dstConfig.GetDstConfig(clusterName) var masterModFilePath, caveModFilePath string if config.Ugc_directory != "" { masterModFilePath = filepath.Join(s.pathResolver.GetUgcModPath(clusterName), "content", "322330", modid) caveModFilePath = filepath.Join(s.pathResolver.GetUgcModPath(clusterName), "content", "322330", modid) } else { masterModFilePath = filepath.Join(config.Force_install_dir, "ugc_mods", clusterName, "Master", "content", "322330", modid) caveModFilePath = filepath.Join(config.Force_install_dir, "ugc_mods", clusterName, "Caves", "content", "322330", modid) } if fileUtils.Exists(masterModFilePath) { return masterModFilePath, true } if fileUtils.Exists(caveModFilePath) { return caveModFilePath, true } return "", false } // readModInfo 读取modinfo.lua文件 func (s *ModService) readModInfo(lang, modId, modinfoPath string) map[string]interface{} { script, err := ioutil.ReadFile(modinfoPath) if err != nil { log.Println("Error reading modinfo.lua:", err) return make(map[string]interface{}) } return s.parseModInfoLua(lang, modId, string(script)) } // parseModInfoLua 解析modinfo.lua文件 func (s *ModService) parseModInfoLua(lang, modId, script string) map[string]interface{} { L := lua.NewState() defer L.Close() L.SetGlobal("locale", lua.LString(lang)) L.SetGlobal("folder_name", lua.LString(fmt.Sprintf("workshop-%s", modId))) L.SetGlobal("ChooseTranslationTable", L.NewFunction(func(L *lua.LState) int { tbl := L.ToTable(1) langTbl := tbl.RawGetString(lang) if langTbl != lua.LNil { L.Push(langTbl) } else { L.Push(tbl.RawGetInt(1)) } return 1 })) L.DoString(script) global := L.Get(lua.GlobalsIndex).(*lua.LTable) m := make(map[string]interface{}) global.ForEach(func(k lua.LValue, v lua.LValue) { if !excludeList[k.String()] && v.Type() != lua.LTFunction { m[k.String()] = toInterface(v) } }) return m } // getVersion 从tags中获取版本号 func (s *ModService) getVersion(tags interface{}) string { tagList, ok := tags.([]interface{}) if !ok { return "" } for _, tag := range tagList { tagMap, ok := tag.(map[string]interface{}) if !ok { continue } tagStr, ok := tagMap["tag"].(string) if !ok { continue } if len(tagStr) > 8 && tagStr[:8] == "version:" { return tagStr[8:] } } return "" } // searchModInfoByWorkshopId 通过workshopId搜索mod信息 func (s *ModService) searchModInfoByWorkshopId(modID int) ModInfo { urlStr := "http://api.steampowered.com/IPublishedFileService/GetDetails/v1/" data := url.Values{} data.Set("key", steamAPIKey) data.Set("language", "6") data.Set("publishedfileids[0]", strconv.Itoa(modID)) urlStr = urlStr + "?" + data.Encode() req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return ModInfo{} } client := &http.Client{} resp, err := client.Do(req) if err != nil { return ModInfo{} } defer resp.Body.Close() var result map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return ModInfo{} } dataList, ok := result["response"].(map[string]interface{})["publishedfiledetails"].([]interface{}) if !ok || len(dataList) == 0 { return ModInfo{} } data2 := dataList[0].(map[string]interface{}) if data2["consumer_appid"] == nil || data2["consumer_appid"].(float64) != 322330 { return ModInfo{} } img := data2["preview_url"].(string) auth := data2["creator"].(string) var authorURL string if auth != "" { authorURL = fmt.Sprintf("https://steamcommunity.com/profiles/%s/?xml=1", auth) } modId := data2["publishedfileid"].(string) name := data2["title"].(string) description := data2["file_description"].(string) img = fmt.Sprintf("%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true", img) return ModInfo{ ID: modId, Name: name, Author: authorURL, Desc: description, Time: int(data2["time_updated"].(float64)), Sub: int(data2["subscriptions"].(float64)), Img: img, } } // getLocalModInfo 获取本地mod信息 func (s *ModService) getLocalModInfo(clusterName, lang, modId string) (*model.ModInfo, error) { modConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modId)) modConfig := string(modConfigJson) newModInfo := &model.ModInfo{ Auth: "", ConsumerAppid: 0, CreatorAppid: 0, Description: "", Modid: modId, Img: "xxx", LastTime: 0, Name: modId, V: "", ModConfig: modConfig, } err := s.db.Create(newModInfo).Error return newModInfo, err } // addModInfoToDb 添加mod信息到数据库 func (s *ModService) addModInfoToDb(clusterName, lang, modid string) error { var modInfo *model.ModInfo var err error if !isWorkshopId(modid) { modInfo, err = s.getLocalModInfo(clusterName, lang, modid) } else { // 从Steam获取mod基本信息 modInfo, err = s.getModInfo2(modid) } if err != nil { return fmt.Errorf("获取modinfo失败: %w", err) } // 从数据库查找是否已存在 oldModinfo, err := s.GetModByModId(modid) var modConfig string modConfigJson, _ := json.Marshal(s.getModInfoConfig(clusterName, lang, modid)) modConfig = string(modConfigJson) if err == nil && oldModinfo.Modid != "" { // 更新 oldModinfo.LastTime = modInfo.LastTime oldModinfo.Name = modInfo.Name oldModinfo.Auth = modInfo.Auth oldModinfo.Description = modInfo.Description oldModinfo.Img = modInfo.Img oldModinfo.V = modInfo.V oldModinfo.ModConfig = modConfig return s.db.Save(oldModinfo).Error } // 新增 modInfo.ModConfig = modConfig return s.db.Create(modInfo).Error } // getModInfo2 从Steam API获取mod基本信息 func (s *ModService) getModInfo2(modID string) (*model.ModInfo, error) { urlStr := "http://api.steampowered.com/IPublishedFileService/GetDetails/v1/" data := url.Values{} data.Set("key", steamAPIKey) data.Set("language", "6") data.Set("publishedfileids[0]", modID) urlStr = urlStr + "?" + data.Encode() req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, err } client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var result map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return nil, err } dataList, ok := result["response"].(map[string]interface{})["publishedfiledetails"].([]interface{}) if !ok || len(dataList) == 0 { return nil, errors.New("获取mod信息失败") } data2 := dataList[0].(map[string]interface{}) img := data2["preview_url"].(string) auth := data2["creator"].(string) var authorURL string if auth != "" { authorURL = fmt.Sprintf("https://steamcommunity.com/profiles/%s/?xml=1", auth) } modId := data2["publishedfileid"].(string) name := data2["title"].(string) lastTime := data2["time_updated"].(float64) description := data2["file_description"].(string) fileUrl := data2["file_url"] img = fmt.Sprintf("%s?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%%23000000&letterbox=true", img) v := s.getVersion(data2["tags"]) creatorAppid := data2["creator_appid"].(float64) consumerAppid := data2["consumer_appid"].(float64) var fileUrlStr = "" if fileUrl != nil { fileUrlStr = fileUrl.(string) } return &model.ModInfo{ Auth: authorURL, ConsumerAppid: consumerAppid, CreatorAppid: creatorAppid, Description: description, FileUrl: fileUrlStr, Modid: modId, Img: img, LastTime: lastTime, Name: name, V: v, }, nil } // getPublishedFileDetailsBatched 批量获取mod详情 func (s *ModService) getPublishedFileDetailsBatched(workshopIds []string, batchSize int) ([]Publishedfiledetail, error) { var allPublishedFileDetails []Publishedfiledetail for i := 0; i < len(workshopIds); i += batchSize { end := i + batchSize if end > len(workshopIds) { end = len(workshopIds) } batch := workshopIds[i:end] publishedFileDetails, err := s.getPublishedFileDetailsWithGet(batch) if err != nil { return nil, err } allPublishedFileDetails = append(allPublishedFileDetails, publishedFileDetails...) } return allPublishedFileDetails, nil } // getPublishedFileDetailsWithGet 通过GET方式获取mod详情 func (s *ModService) getPublishedFileDetailsWithGet(workshopIds []string) ([]Publishedfiledetail, error) { urlStr := "http://api.steampowered.com/IPublishedFileService/GetDetails/v1/" data := url.Values{} data.Set("key", steamAPIKey) data.Set("language", "6") for i := range workshopIds { data.Set("publishedfileids["+strconv.Itoa(i)+"]", workshopIds[i]) } urlStr = urlStr + "?" + data.Encode() req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, err } client := &http.Client{} res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close() var publishedFileDetailsData struct { Response struct { Publishedfiledetails []Publishedfiledetail `json:"publishedfiledetails"` } `json:"response"` } err = json.NewDecoder(res.Body).Decode(&publishedFileDetailsData) if err != nil { return nil, err } return publishedFileDetailsData.Response.Publishedfiledetails, nil } // getPublishedFileDetails 通过POST方式获取mod详情 func (s *ModService) getPublishedFileDetails(workshopIds []string) ([]Publishedfiledetail, error) { url := "https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/" payload := &bytes.Buffer{} writer := multipart.NewWriter(payload) _ = writer.WriteField("itemcount", strconv.Itoa(len(workshopIds))) for i := range workshopIds { _ = writer.WriteField("publishedfileids["+strconv.Itoa(i)+"]", workshopIds[i]) } err := writer.Close() if err != nil { return nil, err } tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: tr} req, err := http.NewRequest("POST", url, payload) if err != nil { return nil, err } req.Header.Set("Content-Type", writer.FormDataContentType()) res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close() var publishedFileDetailsData struct { Response struct { Result int `json:"result"` Resultcount int `json:"resultcount"` Publishedfiledetails []Publishedfiledetail `json:"publishedfiledetails"` } `json:"response"` } err = json.NewDecoder(res.Body).Decode(&publishedFileDetailsData) if err != nil { return nil, err } if publishedFileDetailsData.Response.Result == 1 { return publishedFileDetailsData.Response.Publishedfiledetails, nil } return nil, errors.New("请求失败") } // unzipToDir 解压zip文件到指定目录 func (s *ModService) unzipToDir(zipReader *zip.Reader, destDir string) error { for _, file := range zipReader.File { destPath := filepath.Join(destDir, file.Name) if !filepath.HasPrefix(destPath, filepath.Clean(destDir)+string(os.PathSeparator)) { return fmt.Errorf("非法文件路径: %s", destPath) } if file.FileInfo().IsDir() { err := os.MkdirAll(destPath, os.ModePerm) if err != nil { return err } continue } if err := os.MkdirAll(filepath.Dir(destPath), os.ModePerm); err != nil { return err } outFile, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode()) if err != nil { return err } defer outFile.Close() rc, err := file.Open() if err != nil { return err } defer rc.Close() _, err = io.Copy(outFile, rc) if err != nil { return err } } return nil } // ===== 辅助函数 ===== // excludeList Lua自带对象名称 var excludeList = map[string]bool{ "_G": true, "assert": true, "collectgarbage": true, "dofile": true, "error": true, "getmetatable": true, "ipairs": true, "load": true, "loadfile": true, "module": true, "next": true, "pairs": true, "pcall": true, "print": true, "rawequal": true, "rawget": true, "rawset": true, "require": true, "select": true, "setmetatable": true, "tonumber": true, "tostring": true, "type": true, "unpack": true, "xpcall": true, "debug": true, "_VERSION": true, "os": true, "_GOPHER_LUA_VERSION": true, "string": true, "math": true, "io": true, "channel": true, "package": true, "coroutine": true, "table": true, } // toInterface 将Lua值转换为interface{} func toInterface(lv lua.LValue) interface{} { switch lv.Type() { case lua.LTNil: return nil case lua.LTBool: return bool(lv.(lua.LBool)) case lua.LTNumber: return float64(lv.(lua.LNumber)) case lua.LTString: return lv.String() case lua.LTTable: t := lv.(*lua.LTable) if isTableArray(t) { arr := make([]interface{}, t.Len()) t.ForEach(func(i lua.LValue, v lua.LValue) { index := int(float64(i.(lua.LNumber)) - 1) if index != -1 && index < len(arr) { arr[index] = toInterface(v) } }) return arr } return toMap(t) default: return lv.String() } } // toMap 将Lua table转换为map func toMap(t *lua.LTable) map[string]interface{} { m := make(map[string]interface{}) t.ForEach(func(k lua.LValue, v lua.LValue) { key := "" switch k.Type() { case lua.LTString: key = k.String() case lua.LTNumber: key = fmt.Sprintf("%g", float64(k.(lua.LNumber))) default: key = fmt.Sprintf("%v", k) } m[key] = toInterface(v) }) return m } // isTableArray 判断Lua table是否为数组 func isTableArray(t *lua.LTable) bool { maxIndex := 0 isSequential := true t.ForEach(func(k lua.LValue, v lua.LValue) { if i, ok := k.(lua.LNumber); ok { if i != lua.LNumber(int(i)) { isSequential = false } else if int(i) > maxIndex { maxIndex = int(i) } } else { isSequential = false } }) return isSequential && maxIndex == t.Len() } // isWorkshopId 判断是否为workshop ID func isWorkshopId(id string) bool { _, err := strconv.Atoi(id) return err == nil } // isModId 判断字符串是否为modID func isModId(str string) (int, bool) { id, err := strconv.Atoi(str) return id, err == nil } ================================================ FILE: internal/service/player/player_service.go ================================================ package player import ( "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/archive" "dst-admin-go/internal/service/game" "log" "regexp" "strconv" "strings" "time" ) // PlayerInfo 玩家信息结构体 type PlayerInfo struct { Key string `json:"key"` Day string `json:"day"` KuId string `json:"kuId"` Name string `json:"name"` Role string `json:"role"` } type PlayerService struct { archive *archive.PathResolver } func NewPlayerService(archive *archive.PathResolver) *PlayerService { return &PlayerService{ archive: archive, } } func (p *PlayerService) GetPlayerList(clusterName string, levelName string, gameProcess game.Process) []PlayerInfo { // 处理 #ALL_LEVEL 情况 queryName := "" if levelName == "#ALL_LEVEL" { queryName = "Master" } else { queryName = levelName } status, _ := gameProcess.Status(clusterName, queryName) if !status { return make([]PlayerInfo, 0) } id := strconv.FormatInt(time.Now().Unix(), 10) command := "" if levelName == "#ALL_LEVEL" { levelName = "Master" command = "for i, v in ipairs(TheNet:GetClientTable()) do print(string.format(\\\"player: {[%s] [%d] [%s] [%s] [%s] [%s]} \\\", " + "'" + id + "'" + ",i-1, string.format('%03d', v.playerage), v.userid, v.name, v.prefab)) end" } else { command = "for i, v in ipairs(AllPlayers) do print(string.format(\\\"player: {[%d] [%d] [%d] [%s] [%s] [%s]} \\\", " + id + ",i,v.components.age:GetAgeInDays(), v.userid, v.name, v.prefab)) end" } err := gameProcess.Command(clusterName, levelName, command) log.Println("clusterName:", clusterName, "levelName:", levelName, "command:", command) if err != nil { log.Println("Error sending command:", err) return make([]PlayerInfo, 0) } time.Sleep(time.Duration(1) * time.Second) // 读取日志 serverLogPath := p.archive.ServerLogPath(clusterName, levelName) dstLogs, err := fileUtils.ReverseRead(serverLogPath, 1000) playerInfoList := make([]PlayerInfo, 0) for _, line := range dstLogs { if strings.Contains(line, id) && strings.Contains(line, "KU") && !strings.Contains(line, "Host") { log.Println(line) // 提取 {} 中的内容 reCurlyBraces := regexp.MustCompile(`\{([^}]*)\}`) curlyBracesMatches := reCurlyBraces.FindStringSubmatch(line) if len(curlyBracesMatches) > 1 { // curlyBracesMatches[1] 包含 {} 中的内容 contentInsideCurlyBraces := curlyBracesMatches[1] // 提取 [] 中的内容 reSquareBrackets := regexp.MustCompile(`\[([^\]]*)\]`) squareBracketsMatches := reSquareBrackets.FindAllStringSubmatch(contentInsideCurlyBraces, -1) var result []string for _, match := range squareBracketsMatches { // match[1] 包含 [] 中的内容 contentInsideSquareBrackets := match[1] result = append(result, contentInsideSquareBrackets) } if len(result) >= 6 { playerInfo := PlayerInfo{Key: result[1], Day: result[2], KuId: result[3], Name: result[4], Role: result[5]} playerInfoList = append(playerInfoList, playerInfo) } } } } // 创建一个map,用于存储不重复的KuId和对应的PlayerInfo对象 uniquePlayers := make(map[string]PlayerInfo) // 遍历players切片 for _, player := range playerInfoList { // 将PlayerInfo对象添加到map中,以KuId作为键 uniquePlayers[player.KuId] = player } // 将不重复的PlayerInfo对象从map中提取到新的切片中 filteredPlayers := make([]PlayerInfo, 0, len(uniquePlayers)) for _, player := range uniquePlayers { filteredPlayers = append(filteredPlayers, player) } return filteredPlayers } func (p *PlayerService) GetPlayerAllList(clusterName string, gameProcess game.Process) []PlayerInfo { // 使用 #ALL_LEVEL 调用 GetPlayerList,获取所有玩家 return p.GetPlayerList(clusterName, "#ALL_LEVEL", gameProcess) } ================================================ FILE: internal/service/update/factory.go ================================================ package update import ( "dst-admin-go/internal/pkg/utils" "dst-admin-go/internal/service/dstConfig" ) func NewUpdateService(dstConfig dstConfig.Config) Update { isWindow := utils.IsWindow() if isWindow { return NewWindowUpdate(dstConfig) } return NewLinuxUpdate(dstConfig) } ================================================ FILE: internal/service/update/linux_update.go ================================================ package update import ( "dst-admin-go/internal/pkg/utils/shellUtils" "dst-admin-go/internal/service/dstConfig" "log" ) type LinuxUpdate struct { dstConfig dstConfig.Config } func NewLinuxUpdate(dstConfig dstConfig.Config) *LinuxUpdate { return &LinuxUpdate{ dstConfig: dstConfig, } } func (u LinuxUpdate) Update(clusterName string) error { config, err := u.dstConfig.GetDstConfig(clusterName) if err != nil { return err } updateCommand, err := LinuxUpdateCommand(config) if err != nil { return err } log.Println("正在更新游戏", "cluster: ", clusterName, "command: ", updateCommand) _, err = shellUtils.Shell(updateCommand) return err } ================================================ FILE: internal/service/update/update.go ================================================ package update import ( "dst-admin-go/internal/pkg/utils/fileUtils" "dst-admin-go/internal/service/dstConfig" "fmt" "path/filepath" "runtime" "strings" ) type Update interface { Update(clusterName string) error } func EscapePath(path string) string { if runtime.GOOS == "windows" { return path } // 在这里添加需要转义的特殊字符 escapedChars := []string{" ", "'", "(", ")"} for _, char := range escapedChars { path = strings.ReplaceAll(path, char, "\\"+char) } return path } func GetBaseUpdateCmd(cluster dstConfig.DstConfig) string { steamCmdPath := cluster.Steamcmd dstInstallDir := cluster.Force_install_dir if cluster.Beta == 1 { dstInstallDir = dstInstallDir + "-beta" } // 确保路径是跨平台兼容的 dstInstallDir = filepath.Clean(EscapePath(dstInstallDir)) steamCmdPath = filepath.Clean(steamCmdPath) // 构建基本命令 baseCmd := "+login anonymous +force_install_dir %s +app_update 343050" if cluster.Beta == 1 { baseCmd += " -beta updatebeta" } baseCmd += " validate +quit" baseCmd = fmt.Sprintf(baseCmd, dstInstallDir) return baseCmd } func WindowUpdateCommand(cluster dstConfig.DstConfig) (string, error) { steamCmdPath := cluster.Steamcmd baseCmd := GetBaseUpdateCmd(cluster) var cmd string cmd = fmt.Sprintf("cd /d %s && Start steamcmd.exe %s", steamCmdPath, baseCmd) return cmd, nil } func LinuxUpdateCommand(cluster dstConfig.DstConfig) (string, error) { steamCmdPath := cluster.Steamcmd baseCmd := GetBaseUpdateCmd(cluster) var cmd string steamCmdScript := filepath.Join(steamCmdPath, "steamcmd.sh") if cluster.Bin == 86 { cmd = fmt.Sprintf("cd %s ; box86 ./linux32/steamcmd %s", steamCmdPath, baseCmd) } else { if fileUtils.Exists(steamCmdScript) { cmd = fmt.Sprintf("cd %s ; ./steamcmd.sh %s", steamCmdPath, baseCmd) } else { cmd = fmt.Sprintf("cd %s ; ./steamcmd %s", steamCmdPath, baseCmd) } } return cmd, nil } ================================================ FILE: internal/service/update/window_update.go ================================================ package update import ( "dst-admin-go/internal/pkg/utils/shellUtils" "dst-admin-go/internal/service/dstConfig" "log" ) type WindowUpdate struct { dstConfig dstConfig.Config } func NewWindowUpdate(dstConfig dstConfig.Config) *WindowUpdate { return &WindowUpdate{ dstConfig: dstConfig, } } func (u WindowUpdate) Update(clusterName string) error { config, err := u.dstConfig.GetDstConfig(clusterName) if err != nil { return err } updateCommand, err := WindowUpdateCommand(config) if err != nil { return err } log.Println("正在更新游戏", "cluster: ", clusterName, "command: ", updateCommand) result, err := shellUtils.ExecuteCommandInWin(updateCommand) log.Println(result) return err } ================================================ FILE: scripts/build_linux.sh ================================================ rm -rf dst-admin-go GOOS=linux GOARCH=amd64 go build -o dst-admin-go cmd/server/main.go ================================================ FILE: scripts/build_swagger.sh ================================================ swag init -g cmd/server/main.go -o docs ================================================ FILE: scripts/build_window.sh ================================================ GOOS=windows GOARCH=amd64 go build -o dst-admin-go.exe cmd/server/main.go ================================================ FILE: scripts/docker/Dockerfile ================================================ # 使用官方的Ubuntu基础镜像 FROM ubuntu:20.04 LABEL maintainer="hujinbo23 jinbohu23@outlook.com" LABEL description="DoNotStarveTogehter server panel written in golang. github: https://github.com/hujinbo23/dst-admin-go" # 更新并安装必要的软件包 RUN dpkg --add-architecture i386 && \ apt-get update && \ apt-get install -y \ curl \ libcurl4-gnutls-dev:i386 \ lib32gcc1 \ lib32stdc++6 \ libcurl4-gnutls-dev \ libgcc1 \ libstdc++6 \ wget \ ca-certificates \ screen \ procps \ sudo \ unzip \ && rm -rf /var/lib/apt/lists/* # 设置工作目录 WORKDIR /app # 拷贝程序二进制文件 COPY dst-admin-go /app/dst-admin-go RUN chmod 755 /app/dst-admin-go COPY docker-entrypoint.sh /app/docker-entrypoint.sh RUN chmod 755 /app/docker-entrypoint.sh COPY config.yml /app/config.yml COPY docker_dst_config /app/dst_config COPY dist /app/dist COPY static /app/static # 内嵌源配置信息 # 控制面板访问的端口 EXPOSE 8082/tcp # 饥荒世界通信的端口 EXPOSE 10888/udp # 饥荒洞穴世界的端口 EXPOSE 10998/udp # 饥荒森林世界的端口 EXPOSE 10999/udp # 运行命令 ENTRYPOINT ["./docker-entrypoint.sh"] ================================================ FILE: scripts/docker/README.md ================================================ # Docker 部署脚本 用于构建 DST Admin Go 的标准 Docker 镜像(Linux x86_64 架构)。 ## 目录内容 - `Dockerfile` - Docker 镜像构建文件(基于 Ubuntu 20.04) - `docker-entrypoint.sh` - 容器启动入口脚本 - `docker_build.sh` - 构建并推送镜像到 Docker Hub 的自动化脚本 - `docker_dst_config` - Docker 环境默认配置文件 ## 快速开始 ### 1. 构建镜像 ```bash # 首先在项目根目录构建 Linux 二进制文件 bash scripts/build_linux.sh # 进入 docker 目录 cd scripts/docker # 构建并推送镜像(需要先登录 Docker Hub) bash docker_build.sh # 示例 bash docker_build.sh 1.6.1 ``` ### 2. 运行容器 ```bash # 创建数据目录 mkdir -p ~/dstsave/{back,steamcmd,dst-dedicated-server} # 运行容器 docker run -d \ --name dst-admin \ -p 8082:8082 \ -p 10888:10888/udp \ -p 10998:10998/udp \ -p 10999:10999/udp \ -v ~/dstsave:/root/.klei/DoNotStarveTogether \ -v ~/dstsave/back:/app/backup \ -v ~/dstsave/steamcmd:/app/steamcmd \ -v ~/dstsave/dst-dedicated-server:/app/dst-dedicated-server \ hujinbo23/dst-admin-go:latest ``` ### 3. 访问管理面板 打开浏览器访问: http://localhost:8082 ## 端口说明 | 端口 | 协议 | 用途 | |-----|------|------| | 8082 | TCP | 管理面板 Web 访问端口 | | 10888 | UDP | 饥荒主世界(Master)通信端口 | | 10998 | UDP | 饥荒洞穴世界(Caves)端口 | | 10999 | UDP | 饥荒森林世界(Forest)端口 | ## 数据卷 容器内重要路径说明: | 容器内路径 | 用途 | 是否推荐挂载 | |-----------|------|-------------| | `/root/.klei/DoNotStarveTogether` | 游戏存档目录 | ✅ 推荐 | | `/app/backup` | 存档备份目录 | ✅ 推荐 | | `/app/mod` | MOD 缓存目录 | 可选 | | `/app/steamcmd` | SteamCMD 安装目录 | ✅ 推荐 | | `/app/dst-dedicated-server` | 饥荒服务器文件 | ✅ 推荐 | | `/app/dst-db` | SQLite 数据库文件 | ✅ 推荐 | | `/app/password.txt` | 初始密码文件 | ✅ 推荐 | | `/app/first` | 首次登录标记文件 | ✅ 推荐 | | `/app/dst-admin-go.log` | 应用日志文件 | 可选 | | `/app/config.yml` | 配置文件 | 可选 | **特别说明**: - `first` 文件:如果存在,启动时会跳过初始化界面,使用 `password.txt` 中的账号登录 - `dst-db` 文件:SQLite 数据库,包含所有配置和运行数据 - `password.txt` 文件:初始管理员账号信息,格式见 Docker Compose 示例 ## 镜像特性 - **基础镜像**: Ubuntu 20.04 - **目标架构**: Linux x86_64 (amd64) - **已安装组件**: - curl, wget - 网络工具 - screen - 游戏进程管理 - lib32gcc1, lib32stdc++6 - 32位运行库(饥荒服务器依赖) - libcurl4-gnutls-dev - cURL 开发库 - procps, sudo, unzip - 系统工具 ## 配置自定义 ### 方法一:环境变量 ```bash docker run -d \ -e BIND_ADDRESS="" \ -e PORT=8082 \ -e DATABASE=dst-db \ hujinbo23/dst-admin-go:latest ``` ### 方法二:挂载配置文件 ```bash docker run -d \ -p 8082:8082 \ -p 10888:10888/udp \ -p 10998:10998/udp \ -p 10999:10999/udp \ -v ~/dstsave:/root/.klei/DoNotStarveTogether \ -v ~/dstsave/back:/app/backup \ -v ~/dstsave/steamcmd:/app/steamcmd \ -v ~/dstsave/dst-dedicated-server:/app/dst-dedicated-server \ -v ~/dstsave/config.yml:/app/config.yml \ hujinbo23/dst-admin-go:latest ``` ## Docker Compose 示例 ### 1. 创建前置文件和目录 在使用 Docker Compose 之前,需要先创建必要的文件和目录: ```bash # 创建所有必要的目录 mkdir -p ~/dstsave/back mkdir -p ~/dstsave/steamcmd mkdir -p ~/dstsave/dst-dedicated-server # 创建 first 文件(标记非首次登录,避免进入初始化界面) touch ~/dstsave/first # 创建数据库文件 touch ~/dstsave/dst-db # 创建初始密码文件 cat > ~/dstsave/password.txt << EOF username = admin password = 123456 displayName = admin photoURL = email = xxx EOF ``` **目录结构**: ``` ~/dstsave/ ├── back/ # 备份目录 ├── steamcmd/ # SteamCMD 安装目录 ├── dst-dedicated-server/ # 饥荒服务器文件 ├── dst-db # SQLite 数据库文件 ├── password.txt # 初始密码文件 └── first # 首次登录标记文件 ``` **说明**: - `first` 文件:如果存在则跳过初始化界面,直接使用 `password.txt` 中的账号登录 - `dst-db` 文件:SQLite 数据库文件 - `password.txt` 文件:初始管理员账号信息 ### 2. 创建 docker-compose.yml ```yaml version: '3.8' services: dst-admin: image: hujinbo23/dst-admin-go:latest container_name: dst-admin restart: unless-stopped ports: - "8082:8082" - "10888:10888/udp" - "10998:10998/udp" - "10999:10999/udp" volumes: # 时区同步 - /etc/localtime:/etc/localtime:ro - /etc/timezone:/etc/timezone:ro # 游戏存档目录 - ${PWD}/dstsave:/root/.klei/DoNotStarveTogether # 备份目录 - ${PWD}/dstsave/back:/app/backup # SteamCMD 目录 - ${PWD}/dstsave/steamcmd:/app/steamcmd # 饥荒服务器目录 - ${PWD}/dstsave/dst-dedicated-server:/app/dst-dedicated-server # 数据库文件 - ${PWD}/dstsave/dst-db:/app/dst-db # 初始密码文件 - ${PWD}/dstsave/password.txt:/app/password.txt # 首次登录标记文件 - ${PWD}/dstsave/first:/app/first environment: - TZ=Asia/Shanghai ``` ### 3. 启动容器 ```bash docker-compose up -d ``` ### 4. 查看日志 ```bash # 查看容器日志 docker-compose logs -f # 查看应用日志 docker exec -it dst-admin cat /app/dst-admin-go.log ``` ## 常见问题 ### 容器无法启动 查看日志排查问题: ```bash docker logs dst-admin ``` ### 游戏端口无法访问 1. 确保端口映射正确且使用 UDP 协议 2. 检查宿主机防火墙设置: ```bash # CentOS/RHEL firewall-cmd --add-port=10888/udp --permanent firewall-cmd --reload # Ubuntu/Debian ufw allow 10888/udp ``` ### 数据持久化失败 确保挂载目录有正确的权限: ```bash chmod -R 755 ~/dstsave ``` ### 游戏下载缓慢 首次启动需要下载 SteamCMD 和饥荒服务器文件(约 1-2GB),国内网络可能较慢。可以考虑: 1. 预先下载 SteamCMD 到 `~/dstsave/steamcmd` 目录 2. 预先使用 SteamCMD 下载游戏文件到 `~/dstsave/dst-dedicated-server` 目录 3. 使用代理加速 Steam 下载 ## 性能建议 - **最低配置**: 2 核 CPU, 2GB 内存, 10GB 磁盘 - **推荐配置**: 4 核 CPU, 4GB 内存, 20GB 磁盘 - **生产环境**: 根据玩家数量和世界复杂度适当增加资源 ## 注意事项 1. 生产环境建议使用固定版本标签,避免使用 `latest` 2. 定期备份 `~/dstsave` 目录,里面包含所有重要数据 3. 游戏端口必须使用 UDP 协议,TCP 无法正常工作 4. 容器重启后游戏进程需要手动启动(通过管理面板) 5. 首次启动会自动下载 SteamCMD 和饥荒服务器文件,需要一定时间 6. 所有数据统一存放在 `~/dstsave` 目录,便于管理和备份 ## 相关链接 - [Docker Hub 镜像](https://hub.docker.com/r/hujinbo23/dst-admin-go) - [GitHub 项目主页](https://github.com/hujinbo23/dst-admin-go) - [饥荒联机版官方 Wiki](https://dontstarve.fandom.com/wiki/Don%27t_Starve_Together) ================================================ FILE: scripts/docker/docker-entrypoint.sh ================================================ #!/bin/bash # 修正最大文件描述符数,部分docker版本给的默认值过高,会导致screen运行卡顿 ulimit -Sn 10000 # 获取传入的参数 steam_cmd_path='/app/steamcmd' steam_dst_server='/app/dst-dedicated-server' # 判断 steam_cmd_path 是否存在,不存在则创建 if [ ! -d "$steam_cmd_path" ]; then mkdir -p "$steam_cmd_path" fi # 进入 steam_cmd_path 目录 cd "$steam_cmd_path" # 如果 $steam_dst_server 目录不存在,则下载并解压 SteamCMD 并安装游戏服务器 retry=1 while [ ! -d "${steam_cmd_path}" ] || [ ! -e "${steam_cmd_path}/steamcmd.sh" ]; do if [ $retry -gt 3 ]; then echo "Download steamcmd failed after three times" exit -2 fi echo "Not found steamcmd, start to installing steamcmd, try: ${retry}" wget http://media.steampowered.com/installer/steamcmd_linux.tar.gz -P $steam_cmd_path tar -zxvf $steam_cmd_path/steamcmd_linux.tar.gz -C $steam_cmd_path sleep 3 ((retry++)) done # 如果 $steam_dst_server 目录不存在,则下载并解压 SteamCMD 并安装游戏服务器 retry=1 while [ ! -e "${steam_dst_server}/bin/dontstarve_dedicated_server_nullrenderer" ]; do if [ $retry -gt 3 ]; then echo "Download Dont Starve Together Sever failed after three times" exit -2 fi echo "Not found Dont Starve Together Sever, start to installing, try: ${retry}" bash $steam_cmd_path/steamcmd.sh +force_install_dir $steam_dst_server +login anonymous +app_update 343050 validate +quit mkdir -p $USER_DIR/.klei/DoNotStarveTogether/MyDediServer mkdir -p /app/backup mkdir -p /app/mod echo "username=admin" >> /app/password.txt echo "password=123456" >> /app/password.txt echo "displayName=admin" >> /app/password.txt echo "photoURL=xxx" >> /app/password.txt sleep 3 ((retry++)) done # 运行其他命令,这里只是做示例 echo "SteamCMD installed at $steam_cmd_path" echo "SteamDST server installed at $steam_dst_server" cd /app exec ./dst-admin-go ================================================ FILE: scripts/docker/docker_build.sh ================================================ #!/bin/bash # 获取命令行参数 TAG=$1 # 构建镜像 docker build -t hujinbo23/dst-admin-go:$TAG . # 推送镜像到Docker Hub docker push hujinbo23/dst-admin-go:$TAG ================================================ FILE: scripts/docker/docker_dst_config ================================================ steamcmd=/app/steamcmd force_install_dir=/app/dst-dedicated-server cluster=MyDediServer backup=/app/backup mod_download_path=/app/mod bin=32 beta=0 ================================================ FILE: scripts/docker-build-mac/Dockerfile ================================================ FROM ubuntu:22.04 ENV DEBIAN_FRONTEND=noninteractive ENV DST_DIR=/dst-server # ===== 安装必要依赖 ===== RUN apt update && apt install -y --no-install-recommends \ wget screen git unzip curl tar build-essential cmake ca-certificates \ python3 python3-pip tzdata \ && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ && echo "Asia/Shanghai" > /etc/timezone \ && rm -rf /var/lib/apt/lists/* # ===== 安装 .NET 8 runtime(DepotDownloader 依赖) ===== RUN wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O /tmp/packages-microsoft-prod.deb \ && dpkg -i /tmp/packages-microsoft-prod.deb \ && apt update \ && apt install -y dotnet-runtime-8.0 \ && rm -rf /var/lib/apt/lists/* /tmp/packages-microsoft-prod.deb # ===== 安装 box64 ===== RUN git clone https://github.com/ptitSeb/box64.git /opt/box64 \ && mkdir /opt/box64/build && cd /opt/box64/build \ && cmake .. -DARM_DYNAREC=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo \ && make -j$(nproc) \ && make install \ && rm -rf /opt/box64 # ===== 安装 DepotDownloader 最新 Release ===== RUN wget https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-arm64.zip -O /opt/DepotDownloader.zip \ && unzip /opt/DepotDownloader.zip -d /opt/DepotDownloader \ && rm /opt/DepotDownloader.zip # ===== 创建饥荒服务器目录 ===== RUN mkdir -p $DST_DIR WORKDIR /app ENV PATH=/usr/local/bin:$PATH COPY dst-admin-go /app/dst-admin-go RUN chmod 755 /app/dst-admin-go COPY docker-entrypoint.sh /app/docker-entrypoint.sh RUN chmod 755 /app/docker-entrypoint.sh COPY config.yml /app/config.yml COPY docker_dst_config /app/dst_config COPY dist /app/dist COPY static /app/static ENTRYPOINT ["./docker-entrypoint.sh"] ================================================ FILE: scripts/docker-build-mac/README.md ================================================ # Docker 部署脚本(Mac ARM64) 用于在 Mac ARM64(Apple Silicon: M1/M2/M3)平台上构建和运行 DST Admin Go 的特殊 Docker 镜像。 ## 背景说明 饥荒联机版(Don't Starve Together)服务器原生只支持 x86_64 架构,无法直接在 ARM64 设备上运行。本镜像通过 **Box64** 动态翻译技术实现 x86_64 程序在 ARM64 平台上执行,使得 Apple Silicon Mac 也能运行饥荒服务器。 ## 技术架构 ``` ARM64 主机(Apple Silicon Mac) └─> Docker 容器(ARM64) ├─> dst-admin-go(原生 ARM64 Go 程序) ├─> Box64(x86_64 → ARM64 动态翻译层) │ └─> DST Server(x86_64 游戏服务器) └─> DepotDownloader(ARM64 版本,用于下载游戏文件) ``` ## 目录内容 - `Dockerfile` - ARM64 优化的镜像构建文件(Ubuntu 22.04) - `docker-entrypoint.sh` - 容器启动脚本 - `docker_dst_config` - 默认配置文件 - `dst-mac-arm64-env-install.md` - 手动安装环境的详细步骤文档(非 Docker 部署) ## 核心组件 | 组件 | 版本 | 用途 | |-----|------|------| | Box64 | 最新版 | x86_64 到 ARM64 的动态二进制翻译器(启用 ARM_DYNAREC 优化) | | .NET Runtime | 8.0 | DepotDownloader 运行依赖 | | DepotDownloader | 3.4.0 | Steam 内容下载工具(ARM64 版本) | ## 快速开始 ### 1. 构建镜像 ```bash # 在 Mac ARM64 机器上执行 cd scripts/docker-build-mac # 构建镜像 docker build --platform linux/arm64 -t dst-admin-go-arm64:latest . ``` ### 2. 运行容器 ```bash # 创建数据目录 mkdir -p ~/dstsave/{back,dst-dedicated-server} # 运行容器 docker run -d \ --name dst-admin-arm64 \ --platform linux/arm64 \ -p 8082:8082 \ -p 10888:10888/udp \ -p 10998:10998/udp \ -p 10999:10999/udp \ -v ~/dstsave:/root/.klei/DoNotStarveTogether \ -v ~/dstsave/back:/app/backup \ -v ~/dstsave/dst-dedicated-server:/app/dst-dedicated-server \ dst-admin-go-arm64:latest ``` ### 3. 访问管理面板 打开浏览器访问: http://localhost:8082 ## 性能对比 ### 性能表现 | 指标 | x86_64 原生 | ARM64 + Box64 | |-----|------------|---------------| | CPU 性能 | 100% | 60-80% | | 内存占用 | 基准 | +30-40% | | 启动速度 | 快 | 中等 | | 稳定性 | 完美 | 良好(偶尔崩溃) | ### 适用场景 ✅ **推荐用于**: - 开发和测试环境 - 小型私服(<10 人) - 个人学习和实验 ❌ **不推荐用于**: - 大型公开服务器 - 高并发生产环境 - 对性能要求严格的场景 ## 镜像特性 - **基础镜像**: Ubuntu 22.04 - **目标架构**: ARM64 (aarch64) - **时区设置**: Asia/Shanghai - **已安装组件**: - Box64(从源码编译,启用 ARM_DYNAREC 优化) - .NET 8.0 Runtime - DepotDownloader(ARM64 版本) - screen, wget, curl, git - Python 3, pip - build-essential, cmake(用于编译 Box64) ## 环境变量 | 变量名 | 默认值 | 说明 | |-------|--------|------| | `DST_DIR` | `/dst-server` | 饥荒服务器安装目录 | | `DEBIAN_FRONTEND` | `noninteractive` | 非交互式安装模式 | ## Docker Compose 示例 ### 1. 创建前置文件和目录 在使用 Docker Compose 之前,需要先创建必要的文件和目录: ```bash # 创建所有必要的目录 mkdir -p ~/dstsave/back mkdir -p ~/dstsave/dst-dedicated-server # 创建 first 文件(标记非首次登录,避免进入初始化界面) touch ~/dstsave/first # 创建数据库文件 touch ~/dstsave/dst-db # 创建初始密码文件 cat > ~/dstsave/password.txt << EOF username = admin password = 123456 displayName = admin photoURL = email = xxx EOF ``` **目录结构**: ``` ~/dstsave/ ├── back/ # 备份目录 ├── dst-dedicated-server/ # 饥荒服务器文件 ├── dst-db # SQLite 数据库文件 ├── password.txt # 初始密码文件 └── first # 首次登录标记文件 ``` **说明**: - `first` 文件:如果存在则跳过初始化界面,直接使用 `password.txt` 中的账号登录 - `dst-db` 文件:SQLite 数据库文件 - `password.txt` 文件:初始管理员账号信息 - ARM64 版本不使用 SteamCMD,而是通过 DepotDownloader 下载游戏文件 ### 2. 创建 docker-compose.yml ```yaml version: '3.8' services: dst-admin-arm64: image: dst-admin-go-arm64:latest container_name: dst-admin-arm64 platform: linux/arm64 restart: unless-stopped ports: - "8082:8082" - "10888:10888/udp" - "10998:10998/udp" - "10999:10999/udp" volumes: # 时区同步 - /etc/localtime:/etc/localtime:ro - /etc/timezone:/etc/timezone:ro # 游戏存档目录 - ${PWD}/dstsave:/root/.klei/DoNotStarveTogether # 备份目录 - ${PWD}/dstsave/back:/app/backup # 饥荒服务器目录(ARM64 版本使用 DepotDownloader 下载) - ${PWD}/dstsave/dst-dedicated-server:/app/dst-dedicated-server # 数据库文件 - ${PWD}/dstsave/dst-db:/app/dst-db # 初始密码文件 - ${PWD}/dstsave/password.txt:/app/password.txt # 首次登录标记文件 - ${PWD}/dstsave/first:/app/first environment: - TZ=Asia/Shanghai # 为 ARM64 翻译层提供更多资源 deploy: resources: limits: memory: 4G reservations: memory: 2G ``` ### 3. 启动容器 ```bash docker-compose up -d ``` ### 4. 查看日志 ```bash # 查看容器日志 docker-compose logs -f # 查看应用日志 docker exec -it dst-admin-arm64 cat /app/dst-admin-go.log ``` ## 手动安装(非 Docker) 如果需要在 ARM64 Linux 系统上手动部署,请参考 `dst-mac-arm64-env-install.md` 文档。 关键步骤概述: 1. 安装 .NET 8 Runtime 2. 从源码编译安装 Box64(启用 ARM_DYNAREC) 3. 下载 DepotDownloader(ARM64 版本) 4. 使用 DepotDownloader 下载饥荒服务器 5. 配置 Box64 环境变量 ## 故障排查 ### Box64 启动失败 检查 Box64 是否正确安装: ```bash docker exec -it dst-admin-arm64 box64 --version ``` 查看 Box64 日志(如果有): ```bash docker exec -it dst-admin-arm64 cat /var/log/box64.log ``` ### 游戏服务器崩溃 ARM64 翻译层可能遇到兼容性问题,查看容器日志: ```bash # 查看容器日志 docker logs dst-admin-arm64 # 进入容器查看 screen 会话 docker exec -it dst-admin-arm64 screen -ls docker exec -it dst-admin-arm64 screen -r ``` ### 性能不足 优化建议: 1. 增加容器内存限制: `--memory=4g` 2. 减少游戏世界大小和复杂度 3. 减少加载的 MOD 数量 4. 降低玩家数量上限 ### 游戏下载失败 首次启动需要通过 DepotDownloader 下载游戏文件: ```bash # 手动下载游戏文件 docker exec -it dst-admin-arm64 /opt/DepotDownloader/DepotDownloader \ -app 343050 -os linux -osarch 64 -dir /dst-server -validate ``` ## 性能优化建议 ### 1. 资源配置 ```bash docker run -d \ --cpus="4" \ --memory="4g" \ --memory-swap="6g" \ ... # 其他参数 ``` ### 2. Box64 优化 Box64 在构建时已启用以下优化: - `ARM_DYNAREC=ON` - 启用 ARM 动态重编译(显著提升性能) - `CMAKE_BUILD_TYPE=RelWithDebInfo` - 优化构建模式 ### 3. 游戏配置优化 - 选择较小的世界大小(Small/Medium) - 减少世界生成的生物数量 - 避免使用性能密集型 MOD - 限制玩家数量(建议 ≤ 8 人) ## 与标准版对比 | 特性 | 标准版(x86_64) | ARM64 版 | |-----|----------------|----------| | 架构 | x86_64 | ARM64 + Box64 翻译 | | 部署难度 | 简单 | 中等 | | 性能 | 100% | 60-80% | | 内存占用 | 标准 | +30-40% | | 兼容性 | 完美 | 良好(偶尔问题) | | 适用场景 | 生产环境 | 开发/测试/小型服务器 | | 镜像大小 | ~800MB | ~1.2GB | ## 注意事项 1. **仅适用于 Mac ARM64**: M1/M2/M3/M4 系列芯片 2. **首次启动耗时长**: 需要下载约 1-2GB 的游戏文件 3. **不建议生产环境**: 性能和稳定性不如原生 x86_64 4. **内存需求高**: 建议至少 4GB 可用内存 5. **可能的兼容性问题**: 某些 MOD 可能在 Box64 下无法正常工作 6. **崩溃处理**: 游戏崩溃后需要手动重启(通过管理面板) ## 已知限制 - 某些 CPU 密集型 MOD 可能导致性能下降 - 大型世界(Huge)可能出现卡顿 - 多世界(Master + Caves)同时运行时内存压力大 - Box64 翻译层偶尔可能遇到兼容性问题导致崩溃 ## 参考资源 - [Box64 项目](https://github.com/ptitSeb/box64) - x86_64 到 ARM64 翻译器 - [DepotDownloader](https://github.com/SteamRE/DepotDownloader) - Steam 内容下载工具 - [.NET Runtime 下载](https://dotnet.microsoft.com/download/dotnet/8.0) - .NET 8 运行时 - [DST 专用服务器 Wiki](https://dontstarve.fandom.com/wiki/Guides/Don%E2%80%99t_Starve_Together_Dedicated_Servers) ## 支持与反馈 如果在 ARM64 环境下遇到问题,请在 GitHub Issues 中注明: - 设备型号(M1/M2/M3 等) - macOS 版本 - Docker 版本 - 具体的错误日志 由于 ARM64 是实验性支持,某些问题可能无法完全解决。生产环境建议使用标准的 x86_64 版本。 ================================================ FILE: scripts/docker-build-mac/docker-entrypoint.sh ================================================ #!/bin/bash # 修正最大文件描述符数,部分docker版本给的默认值过高,会导致screen运行卡顿 ulimit -Sn 10000 # 启用 amd64 架构 dpkg --add-architecture amd64 # 添加 amd64 源 echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy main universe multiverse restricted deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-updates main universe multiverse restricted deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-security main universe multiverse restricted" > /etc/apt/sources.list.d/amd64.list # 更新源 apt update # 安装 x86_64 运行库 apt install -y libc6:amd64 libstdc++6:amd64 cd /opt/DepotDownloader ./DepotDownloader -app 343050 -os linux -osarch 64 -dir /app/dst-dedicated-server -validate chmod +x /app/dst-dedicated-server/bin64/dontstarve_dedicated_server_nullrenderer_x64 cd /app exec ./dst-admin-go ================================================ FILE: scripts/docker-build-mac/docker_dst_config ================================================ steamcmd=/app/steamcmd force_install_dir=/app/dst-dedicated-server cluster=MyDediServer backup=/app/backup mod_download_path=/app/mod bin=2664 beta=0 ================================================ FILE: scripts/docker-build-mac/dst-mac-arm64-env-install.md ================================================ # dst-mac-arm64-env-install 安装基础依赖 ```shell apt update apt install -y wget unzip tar ``` 下载 DepotDownloader ```shell cd /opt wget https://github.com/SteamRE/DepotDownloader/releases/latest/download/DepotDownloader-linux-arm64.zip -O DepotDownloader.zip || \ wget https://github.com/SteamRE/DepotDownloader/releases/latest/download/DepotDownloader.zip -O DepotDownloader.zip ``` 安装 .NET 运行时 ```shell wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb dpkg -i packages-microsoft-prod.deb apt update apt install -y dotnet-runtime-8.0 ``` 下载 饥荒服务器 ```shell unzip DepotDownloader.zip -d DepotDownloader cd DepotDownloader ./DepotDownloader -app 343050 -os linux -osarch 64 -dir /app/dst-dedicated-server -validate ``` ``` apt update apt install -y git cmake build-essential # 克隆源码 git clone https://github.com/ptitSeb/box64.git /opt/box64 cd /opt/box64 # 创建构建目录 mkdir build && cd build # 配置并启用 ARM 动态编译器(性能更好) cmake .. -DARM_DYNAREC=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo # 编译 make -j$(nproc) # 安装 make install cp box64 /usr/local/bin/ ``` ``` # 启用 amd64 架构 dpkg --add-architecture amd64 # 添加 amd64 源 echo "deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy main universe multiverse restricted deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-updates main universe multiverse restricted deb [arch=amd64] http://archive.ubuntu.com/ubuntu jammy-security main universe multiverse restricted" > /etc/apt/sources.list.d/amd64.list # 更新源 apt update # 安装 x86_64 运行库 apt install -y libc6:amd64 libstdc++6:amd64 ``` ================================================ FILE: scripts/py-dst-cli/README.md ================================================ # py-dst-cli Python 工具集,用于解析和处理饥荒联机版(Don't Starve Together)的各类配置文件、MOD 信息和游戏资源。 ## 功能概述 本工具提供以下核心功能: 1. **世界配置解析** - 解析和生成 `leveldataoverride.lua` 配置文件 2. **MOD 信息提取** - 从 Steam Workshop 获取 MOD 详细信息 3. **游戏版本查询** - 获取当前最新的饥荒服务器版本号 4. **物品数据解析** - 解析 TooManyItemPlus 等 MOD 的物品数据 5. **资源提取** - 从游戏文件中提取图片资源(worldgen_customization.tex) ## 目录结构 ``` py-dst-cli/ ├── main.py # 主入口程序 ├── dst_version.py # 版本查询工具 ├── parse_world_setting.py # 世界配置解析器 ├── parse_mod.py # MOD 信息解析器 ├── parse_TooManyItemPlus_items.py # 物品数据解析器 ├── parse_world_webp.py # 世界图片资源处理 ├── dst_world_setting.json # 世界配置 JSON 数据 ├── requirements.txt # Python 依赖列表 └── steamapikey.txt # Steam API Key 配置 ``` ## 安装依赖 ### 方法一:使用虚拟环境(推荐) ```bash # 创建虚拟环境 python3 -m venv env # 激活虚拟环境 source env/bin/activate # Linux/Mac # 或 env\Scripts\activate # Windows # 安装依赖库 pip install -r requirements.txt # 使用完毕后退出虚拟环境 deactivate ``` ### 方法二:直接安装 ```bash pip install -r requirements.txt ``` ### 更新依赖列表 如果添加了新的依赖,使用以下命令更新 `requirements.txt`: ```bash pip freeze > requirements.txt ``` ## 使用方法 ### 1. 配置 Steam API Key 在 `steamapikey.txt` 文件中配置你的 Steam Web API Key: ``` YOUR_STEAM_API_KEY_HERE ``` 获取 API Key: https://steamcommunity.com/dev/apikey ### 2. 运行主程序 ```bash python main.py ``` ### 3. 单独使用各个工具 #### 查询游戏版本 ```bash python dst_version.py ``` 输出示例: ```json { "version": "573123", "update_time": "2024-01-15 10:30:00" } ``` #### 解析世界配置 ```bash python parse_world_setting.py ``` 生成标准的 `dst_world_setting.json` 配置文件供管理面板使用。 #### 解析 MOD 信息 ```bash python parse_mod.py ``` 示例: ```bash python parse_mod.py 375859599 # 解析 Global Positions MOD ``` #### 解析物品数据 ```bash python parse_TooManyItemPlus_items.py ``` 从 TooManyItemPlus MOD 中提取物品列表和属性。 #### 处理世界图片资源 ```bash python parse_world_webp.py ``` 将 worldgen_customization.tex 文件转换为可用的图片格式。 ## 获取游戏资源文件 ### 方法一:从游戏安装目录获取 如果已安装饥荒联机版,可直接从安装目录获取: **Windows:** ``` C:\Program Files (x86)\Steam\steamapps\common\Don't Starve Together\data\images ``` **Linux:** ``` ~/.steam/steam/steamapps/common/Don't Starve Together/data/images ``` **Mac:** ``` ~/Library/Application Support/Steam/steamapps/common/Don't Starve Together/data/images ``` 关键文件: - `worldgen_customization.tex` - 世界生成配置界面资源 ### 方法二:通过 SteamCMD 下载 ```bash # 安装 SteamCMD # Ubuntu/Debian: sudo apt install steamcmd # 下载游戏文件 steamcmd +login anonymous +app_update 343050 validate +quit # 游戏文件位置: # Linux: ~/.steam/steam/steamapps/common/Don't Starve Together/ ``` ### 方法三:使用 DepotDownloader ```bash # 下载 DepotDownloader wget https://github.com/SteamRE/DepotDownloader/releases/latest/download/DepotDownloader.zip # 解压并运行 unzip DepotDownloader.zip -d DepotDownloader cd DepotDownloader # 下载饥荒服务器文件 ./DepotDownloader -app 343050 -os linux -osarch 64 -dir ./dst-server -validate ``` ## 常见配置项说明 ### 世界配置(leveldataoverride.lua) 主要配置项: - `world_size` - 世界大小: small/medium/large/huge - `season_start` - 起始季节: autumn/winter/spring/summer - `day` - 昼夜长度设置 - `weather` - 天气频率 - `resources` - 资源丰富度 - `creatures` - 生物数量 - `branching` - 地图分支复杂度 ### MOD 配置(modoverrides.lua) 从 Steam Workshop 获取 MOD 配置选项,支持: - MOD 名称、描述、作者 - 配置项列表和默认值 - 订阅数、更新时间 - 兼容性标签 ## 依赖库 主要 Python 库: - `requests` - HTTP 请求,用于 Steam API 调用 - `beautifulsoup4` - HTML 解析 - `Pillow` - 图片处理 - 其他工具库 ## 与 DST Admin Go 集成 本工具集的输出数据会被 DST Admin Go 的以下模块使用: - `internal/service/levelConfig/` - 世界配置管理 - `internal/service/mod/` - MOD 管理 - `internal/service/update/` - 游戏更新检测 - `internal/api/handler/dst_map_handler.go` - 地图生成 ## 输出格式 所有工具默认输出 JSON 格式数据,可直接被 DST Admin Go 管理面板使用: ```json { "success": true, "data": { ... }, "message": "操作成功" } ``` ## 故障排查 ### 无法获取 MOD 信息 - 检查 `steamapikey.txt` 是否正确配置 - 确认网络可以访问 Steam API - 检查 MOD ID 是否有效 - Steam API 可能有速率限制,稍后重试 ### 版本查询失败 - Steam 服务器可能暂时不可用,稍后重试 - 检查防火墙是否拦截了 Steam 相关域名 - 尝试使用代理访问 ### 依赖安装失败 ```bash # 升级 pip 到最新版本 pip install --upgrade pip # 使用国内镜像源(清华大学) pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple # 或使用阿里云镜像 pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ ``` ### 图片资源转换失败 - 确保安装了 Pillow 库:`pip install Pillow` - 检查源文件格式是否正确 - 某些 .tex 文件可能需要特定的转换工具 ## 常见用例 ### 1. 批量查询 MOD 信息 ```bash # 创建 MOD ID 列表 echo "375859599" > mod_list.txt echo "462372013" >> mod_list.txt # 循环查询 while read mod_id; do python parse_mod.py $mod_id done < mod_list.txt ``` ### 2. 定时检查游戏版本更新 ```bash # 添加到 crontab(每小时检查一次) 0 * * * * cd /path/to/py-dst-cli && python dst_version.py >> version_log.txt ``` ### 3. 导出世界配置模板 ```bash python parse_world_setting.py > world_template.json ``` ## 注意事项 1. **Steam API 限制**: Steam Web API 有频率限制(每天 100,000 次调用),请勿频繁调用 2. **网络要求**: 部分功能需要访问 Steam 服务器,确保网络畅通 3. **编码问题**: 处理中文 MOD 时注意字符编码(统一使用 UTF-8) 4. **虚拟环境**: 建议使用虚拟环境隔离依赖,避免污染系统 Python 环境 5. **API Key 安全**: 不要将 `steamapikey.txt` 提交到公开仓库 ## 开发者信息 本工具集用于辅助 DST Admin Go 项目,提供游戏数据的离线解析和在线查询能力。 相关项目: - [DST Admin Go](https://github.com/hujinbo23/dst-admin-go) - 主项目 - [Steam Web API](https://steamcommunity.com/dev) - Steam API 文档 - [Don't Starve Together Wiki](https://dontstarve.fandom.com/wiki/Don%27t_Starve_Together) - 游戏官方 Wiki ## 贡献指南 如果需要添加新功能: 1. 在对应的 Python 文件中添加函数 2. 更新 `main.py` 以集成新功能 3. 更新 `requirements.txt`(如果有新依赖) 4. 更新本 README 文档 ================================================ FILE: scripts/py-dst-cli/dst_version.py ================================================ import steam.client import steam.client.cdn import steam.core.cm import steam.webapi from steam.exceptions import SteamError def get_dst_version(steamcdn=None): anonymous = steam.client.SteamClient() anonymous.anonymous_login() steamcdn = steam.client.cdn.CDNClient(anonymous) print("开始获取dst版本文件") # 0 下载失败, 1 下载成功, 2 内容为空 for _ in range(3): try: # b = next(steamcdn.get_manifests(343050, filter_func=lambda x, y: x == 343052)) # version = next(b.iter_files('version.txt')).read().decode('utf-8').strip() version = [*steamcdn.iter_files(343050, 'version.txt', filter_func=lambda x, y: x == 343052)] if not version: return 0 version = version[0].read().decode('utf-8').strip() # print(version) return int(version) except SteamError as e: print("get dst version error", SteamError) return 0 return 0 if __name__ == "__main__": print(get_dst_version()) ================================================ FILE: scripts/py-dst-cli/dst_world_setting.json ================================================ {"zh": {"forest": {"WORLDGEN_GROUP": {"monsters": {"order": 5, "text": "敌对生物以及刷新点", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "items": {"spiders": {"image": {"x": 0.9375, "y": 0.375}, "text": "蜘蛛巢", "value": "default"}, "angrybees": {"image": {"x": 0.5, "y": 0.5}, "text": "杀人蜂蜂窝", "value": "default"}, "chess": {"image": {"x": 0.875, "y": 0.0}, "text": "发条装置", "value": "default"}, "tentacles": {"image": {"x": 0.1875, "y": 0.5}, "text": "触手", "value": "default"}, "walrus": {"image": {"x": 0.625, "y": 0.125}, "text": "海象营地", "value": "default"}, "ocean_waterplant": {"image": {"x": 0.0, "y": 0.375}, "text": "海草", "desc": {"ocean_never": "无", "ocean_rare": "很少", "ocean_uncommon": "较少", "ocean_default": "默认", "ocean_often": "较多", "ocean_mostly": "很多", "ocean_always": "大量", "ocean_insane": "疯狂"}, "value": "ocean_default"}, "tallbirds": {"image": {"x": 0.125, "y": 0.5}, "text": "高脚鸟", "value": "default"}, "moon_spiders": {"image": {"x": 0.4375, "y": 0.25}, "text": "破碎蜘蛛洞", "value": "default"}, "houndmound": {"image": {"x": 0.3125, "y": 0.125}, "text": "猎犬丘", "value": "default"}, "merm": {"image": {"x": 0.75, "y": 0.125}, "text": "漏雨的小屋", "value": "default"}}}, "resources": {"order": 3, "text": "资源", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "items": {"moon_starfish": {"image": {"x": 0.5, "y": 0.25}, "text": "海星", "value": "default"}, "rock_ice": {"image": {"x": 0.375, "y": 0.125}, "text": "迷你冰川", "value": "default"}, "moon_sapling": {"image": {"x": 0.375, "y": 0.25}, "text": "月亮树苗", "value": "default"}, "rock": {"image": {"x": 0.5, "y": 0.375}, "text": "巨石", "value": "default"}, "moon_tree": {"image": {"x": 0.5625, "y": 0.25}, "text": "月树", "value": "default"}, "reeds": {"image": {"x": 0.375, "y": 0.375}, "text": "芦苇", "value": "default"}, "cactus": {"image": {"x": 0.5625, "y": 0.0}, "text": "仙人掌", "value": "default"}, "grass": {"image": {"x": 0.25, "y": 0.125}, "text": "草", "value": "default"}, "palmconetree": {"image": {"x": 0.125, "y": 0.375}, "text": "棕榈松果树", "value": "default"}, "ponds": {"image": {"x": 0.25, "y": 0.375}, "text": "池塘", "value": "default"}, "flowers": {"image": {"x": 0.125, "y": 0.125}, "text": "花,邪恶花", "value": "default"}, "ocean_bullkelp": {"image": {"x": 0.75, "y": 0.25}, "text": "公牛海带", "value": "default"}, "trees": {"image": {"x": 0.375, "y": 0.5}, "text": "树(所有)", "value": "default"}, "moon_hotspring": {"image": {"x": 0.25, "y": 0.25}, "text": "温泉", "value": "default"}, "marshbush": {"image": {"x": 0.6875, "y": 0.125}, "text": "尖刺灌木", "value": "default"}, "ocean_seastack": {"image": {"x": 0.875, "y": 0.25}, "text": "海蚀柱", "desc": {"ocean_never": "无", "ocean_rare": "很少", "ocean_uncommon": "较少", "ocean_default": "默认", "ocean_often": "较多", "ocean_mostly": "很多", "ocean_always": "大量", "ocean_insane": "疯狂"}, "value": "ocean_default"}, "tumbleweed": {"image": {"x": 0.4375, "y": 0.5}, "text": "风滚草", "value": "default"}, "moon_berrybush": {"image": {"x": 0.9375, "y": 0.125}, "text": "石果灌木丛", "value": "default"}, "moon_bullkelp": {"image": {"x": 0.0, "y": 0.25}, "text": "海岸公牛海带", "value": "default"}, "mushroom": {"image": {"x": 0.625, "y": 0.25}, "text": "蘑菇", "value": "default"}, "moon_rock": {"image": {"x": 0.3125, "y": 0.25}, "text": "月亮石", "value": "default"}, "carrot": {"image": {"x": 0.625, "y": 0.0}, "text": "胡萝卜", "value": "default"}, "flint": {"image": {"x": 0.0625, "y": 0.125}, "text": "燧石", "value": "default"}, "berrybush": {"image": {"x": 0.3125, "y": 0.0}, "text": "浆果丛", "value": "default"}, "meteorspawner": {"image": {"x": 0.4375, "y": 0.0}, "text": "流星区域", "value": "default"}, "sapling": {"image": {"x": 0.625, "y": 0.375}, "text": "树苗", "value": "default"}}}, "animals": {"order": 4, "text": "生物以及刷新点", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "items": {"ocean_shoal": {"image": {"x": 0.9375, "y": 0.25}, "text": "鱼群", "value": "default"}, "moon_fruitdragon": {"image": {"x": 0.1875, "y": 0.25}, "text": "沙拉蝾螈", "value": "default"}, "rabbits": {"image": {"x": 0.3125, "y": 0.375}, "text": "兔洞", "value": "default"}, "catcoon": {"image": {"x": 0.6875, "y": 0.0}, "text": "空心树桩", "value": "default"}, "ocean_otterdens": {"image": {"x": 0.8125, "y": 0.25}, "text": "水獭掠夺者窝点", "value": "default"}, "ocean_wobsterden": {"image": {"x": 0.0625, "y": 0.375}, "text": "龙虾窝", "value": "default"}, "moles": {"image": {"x": 0.8125, "y": 0.125}, "text": "鼹鼠丘", "value": "default"}, "buzzard": {"image": {"x": 0.5, "y": 0.0}, "text": "秃鹫", "value": "default"}, "moon_carrot": {"image": {"x": 0.0625, "y": 0.25}, "text": "胡萝卜鼠", "value": "default"}, "pigs": {"image": {"x": 0.1875, "y": 0.375}, "text": "猪屋", "value": "default"}, "lightninggoat": {"image": {"x": 0.5625, "y": 0.125}, "text": "伏特羊", "value": "default"}, "beefalo": {"image": {"x": 0.1875, "y": 0.0}, "text": "皮弗娄牛", "value": "default"}, "bees": {"image": {"x": 0.25, "y": 0.0}, "text": "蜜蜂蜂窝", "value": "default"}}}, "misc": {"order": 2, "text": "世界", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": null, "items": {"terrariumchest": {"image": {"x": 0.25, "y": 0.5}, "text": "盒中泰拉", "desc": {"never": "无", "default": "默认"}, "value": "default"}, "prefabswaps_start": {"image": {"x": 0.0625, "y": 0.5}, "text": "开始资源多样化", "desc": {"classic": "经典", "default": "默认", "highly random": "非常随机"}, "order": 20, "value": "default"}, "stageplays": {"image": {"x": 0.0, "y": 0.5}, "text": "舞台剧", "desc": {"never": "无", "default": "默认"}, "value": "default"}, "task_set": {"image": {"x": 0.6875, "y": 0.5}, "text": "生物群系", "desc": {"default": "联机版", "classic": "经典"}, "order": 1, "value": "default"}, "touchstone": {"image": {"x": 0.3125, "y": 0.5}, "text": "试金石", "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "order": 17, "value": "default"}, "world_size": {"image": {"x": 0.75, "y": 0.5}, "text": "世界大小", "desc": {"small": "小", "medium": "中", "default": "大", "huge": "巨大"}, "order": 3, "value": "default"}, "balatro": {"image": {"x": 0.0, "y": 0.0}, "text": "小丑", "desc": {"never": "无", "default": "默认"}, "value": "default"}, "junkyard": {"image": {"x": 0.4375, "y": 0.125}, "text": "垃圾场", "desc": {"never": "无", "default": "默认"}, "value": "default"}, "branching": {"image": {"x": 0.5625, "y": 0.5}, "text": "分支", "desc": {"never": "从不", "least": "最少", "default": "默认", "most": "最多", "random": "随机"}, "order": 4, "value": "default"}, "loop": {"image": {"x": 0.625, "y": 0.5}, "text": "环形", "desc": {"never": "从不", "default": "默认", "always": "总是"}, "order": 5, "value": "default"}, "start_location": {"image": {"x": 0.8125, "y": 0.5}, "text": "出生点", "desc": {"darkness": "黑暗", "default": "默认", "plus": "额外资源"}, "order": 2, "value": "default"}, "moon_fissure": {"image": {"x": 0.125, "y": 0.25}, "text": "天体裂隙", "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "value": "default"}, "roads": {"image": {"x": 0.4375, "y": 0.375}, "text": "道路", "desc": {"never": "无", "default": "默认"}, "order": 6, "value": "default"}, "boons": {"image": {"x": 0.75, "y": 0.375}, "text": "失败的冒险家", "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "order": 18, "value": "default"}}}, "global": {"order": 1, "text": "全局", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": null, "items": {"season_start": {"image": {"x": 0.6875, "y": 0.375}, "text": "起始季节", "desc": {"default": "秋", "winter": "冬", "spring": "春", "summer": "夏", "autumn|spring": "春或秋", "winter|summer": "冬季或夏季", "autumn|winter|spring|summer": "随机"}, "order": 1, "value": "default"}}}}, "WORLDSETTINGS_GROUP": {"survivors": {"order": 2, "text": "冒险家", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"healthpenalty": {"image": {"x": 0.375, "y": 0.1875}, "text": "生命值上限惩罚", "desc": {"none": "禁用", "always": "启用"}, "order": 5, "value": "always"}, "extrastartingitems": {"image": {"x": 0.375, "y": 0.125}, "text": "额外起始资源", "desc": {"0": "总是", "5": "第5天后", "default": "第10天后", "15": "第15天后", "20": "第20天后", "none": "从不"}, "order": 1, "value": "default"}, "spawnprotection": {"image": {"x": 0.875, "y": 0.4375}, "text": "防骚扰出生保护", "desc": {"never": "无", "default": "自动检测", "always": "总是"}, "order": 3, "value": "default"}, "temperaturedamage": {"image": {"x": 0.5625, "y": 0.5}, "text": "温度伤害", "desc": {"nonlethal": "非致命", "default": "默认"}, "order": 7, "value": "default"}, "shadowcreatures": {"image": {"x": 0.375, "y": 0.4375}, "text": "理智怪兽", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "order": 10, "value": "default"}, "darkness": {"image": {"x": 0.5625, "y": 0.0625}, "text": "黑暗伤害", "desc": {"nonlethal": "非致命", "default": "默认"}, "order": 9, "value": "default"}, "seasonalstartingitems": {"image": {"x": 0.3125, "y": 0.4375}, "text": "季节起始物品", "desc": {"never": "无", "default": "默认"}, "order": 2, "value": "default"}, "dropeverythingondespawn": {"image": {"x": 0.0625, "y": 0.125}, "text": "离开游戏后物品掉落", "desc": {"default": "默认", "always": "所有"}, "order": 4, "value": "default"}, "brightmarecreatures": {"image": {"x": 0.9375, "y": 0.0}, "text": "启蒙怪兽", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "order": 11, "value": "default"}, "hunger": {"image": {"x": 0.5625, "y": 0.1875}, "text": "饥饿伤害", "desc": {"nonlethal": "非致命", "default": "默认"}, "order": 8, "value": "default"}, "lessdamagetaken": {"image": {"x": 0.875, "y": 0.1875}, "text": "受到的伤害", "desc": {"always": "较少", "none": "默认", "more": "较多"}, "order": 6, "value": "none"}}}, "global": {"order": 0, "text": "全局", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"specialevent": {"image": {"x": 0.25, "y": 0.125}, "text": "活动", "desc": {"none": "无", "default": "自动"}, "order": 1, "value": "default"}, "ghostenabled": {"image": {"x": 0.9375, "y": 0.125}, "text": "冒险家死亡", "desc": {"none": "更改冒险家", "always": "变鬼魂"}, "order": 8, "value": "always"}, "spawnmode": {"image": {"x": 0.8125, "y": 0.4375}, "text": "出生模式", "desc": {"fixed": "绚丽之门", "scatter": "随机"}, "order": 7, "value": "fixed"}, "portalresurection": {"image": {"x": 0.6875, "y": 0.375}, "text": "在绚丽之门复活", "desc": {"none": "禁用", "always": "启用"}, "order": 9, "value": "none"}, "autumn": {"image": {"x": 0.25, "y": 0.0}, "text": "秋", "desc": {"noseason": "无", "veryshortseason": "极短", "shortseason": "短", "default": "默认", "longseason": "长", "verylongseason": "极长", "random": "随机"}, "order": 2, "value": "default"}, "winter": {"image": {"x": 0.0, "y": 0.5625}, "text": "冬", "desc": {"noseason": "无", "veryshortseason": "极短", "shortseason": "短", "default": "默认", "longseason": "长", "verylongseason": "极长", "random": "随机"}, "order": 3, "value": "default"}, "krampus": {"image": {"x": 0.8125, "y": 0.1875}, "text": "坎普斯", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "order": 13, "value": "default"}, "beefaloheat": {"image": {"x": 0.5625, "y": 0.0}, "text": "皮弗娄牛交配频率", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "order": 12, "value": "default"}, "spring": {"image": {"x": 0.3125, "y": 0.5}, "text": "春", "desc": {"noseason": "无", "veryshortseason": "极短", "shortseason": "短", "default": "默认", "longseason": "长", "verylongseason": "极长", "random": "随机"}, "order": 4, "value": "default"}, "ghostsanitydrain": {"image": {"x": 0.0, "y": 0.1875}, "text": "鬼魂理智值惩罚", "desc": {"none": "禁用", "always": "启用"}, "order": 10, "value": "always"}, "summer": {"image": {"x": 0.4375, "y": 0.5}, "text": "夏", "desc": {"noseason": "无", "veryshortseason": "极短", "shortseason": "短", "default": "默认", "longseason": "长", "verylongseason": "极长", "random": "随机"}, "order": 5, "value": "default"}, "resettime": {"image": {"x": 0.0625, "y": 0.4375}, "text": "死亡重置倒计时", "desc": {"none": "禁用", "slow": "慢", "default": "默认", "fast": "快", "always": "立刻"}, "order": 11, "value": "default"}, "day": {"image": {"x": 0.625, "y": 0.0625}, "text": "昼夜选项", "desc": {"default": "默认", "longday": "长 白天", "longdusk": "长 黄昏", "longnight": "长 夜晚", "noday": "无 白天", "nodusk": "无 黄昏", "nonight": "无 夜晚", "onlyday": "仅 白天", "onlydusk": "仅 黄昏", "onlynight": "仅 夜晚"}, "order": 6, "value": "default"}}}, "resources": {"order": 4, "text": "资源再生", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "veryslow": "极慢", "slow": "慢", "default": "默认", "fast": "快", "veryfast": "极快"}, "items": {"carrots_regrowth": {"image": {"x": 0.1875, "y": 0.0625}, "text": "胡萝卜", "value": "default"}, "basicresource_regrowth": {"image": {"x": 0.375, "y": 0.0}, "text": "基础资源", "desc": {"none": "禁用", "always": "启用"}, "value": "none"}, "cactus_regrowth": {"image": {"x": 0.125, "y": 0.0625}, "text": "仙人掌", "value": "default"}, "deciduoustree_regrowth": {"image": {"x": 0.875, "y": 0.0625}, "text": "桦栗树", "value": "default"}, "palmconetree_regrowth": {"image": {"x": 0.125, "y": 0.375}, "text": "棕榈松果树", "value": "default"}, "flowers_regrowth": {"image": {"x": 0.625, "y": 0.125}, "text": "花", "value": "default"}, "twiggytrees_regrowth": {"image": {"x": 0.75, "y": 0.5}, "text": "多枝树", "value": "default"}, "regrowth": {"image": {"x": 0.0, "y": 0.4375}, "text": "再生速度", "order": 1, "value": "default"}, "moon_tree_regrowth": {"image": {"x": 0.125, "y": 0.3125}, "text": "月树", "value": "default"}, "reeds_regrowth": {"image": {"x": 0.9375, "y": 0.375}, "text": "芦苇", "value": "default"}, "saltstack_regrowth": {"image": {"x": 0.1875, "y": 0.4375}, "text": "盐堆", "value": "default"}, "evergreen_regrowth": {"image": {"x": 0.3125, "y": 0.125}, "text": "常青树", "value": "default"}}}, "events": {"order": 1, "text": "活动", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"default": "默认", "enabled": "总是"}, "items": {"hallowed_nights": {"image": {"x": 0.3125, "y": 0.1875}, "text": "万圣夜", "order": 2, "value": "default"}, "year_of_the_catcoon": {"image": {"x": 0.6875, "y": 0.5625}, "text": "浣猫之年", "order": 9, "value": "default"}, "year_of_the_gobbler": {"image": {"x": 0.375, "y": 0.375}, "text": "火鸡之年", "order": 4, "value": "default"}, "year_of_the_carrat": {"image": {"x": 0.4375, "y": 0.5625}, "text": "胡萝卜鼠之年", "order": 7, "value": "default"}, "year_of_the_snake": {"image": {"x": 0.625, "y": 0.5625}, "text": "洞穴蠕虫之年", "order": 12, "value": "default"}, "crow_carnival": {"image": {"x": 0.5, "y": 0.0625}, "text": "盛夏鸦年华", "order": 1, "value": "default"}, "year_of_the_bunnyman": {"image": {"x": 0.5625, "y": 0.5625}, "text": "兔人之年", "order": 10, "value": "default"}, "year_of_the_pig": {"image": {"x": 0.5625, "y": 0.375}, "text": "猪王之年", "order": 6, "value": "default"}, "year_of_the_varg": {"image": {"x": 0.875, "y": 0.5}, "text": "座狼之年", "order": 5, "value": "default"}, "year_of_the_beefalo": {"image": {"x": 0.375, "y": 0.5625}, "text": "皮弗娄牛之年", "order": 8, "value": "default"}, "year_of_the_dragonfly": {"image": {"x": 0.5, "y": 0.5625}, "text": "龙蝇之年", "order": 11, "value": "default"}, "winters_feast": {"image": {"x": 0.125, "y": 0.5625}, "text": "冬季盛宴", "order": 3, "value": "default"}}}, "giants": {"order": 8, "text": "巨兽", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "items": {"goosemoose": {"image": {"x": 0.125, "y": 0.1875}, "text": "麋鹿鹅", "value": "default"}, "eyeofterror": {"image": {"x": 0.4375, "y": 0.125}, "text": "恐怖之眼", "value": "default"}, "bearger": {"image": {"x": 0.5, "y": 0.0}, "text": "熊獾", "value": "default"}, "deciduousmonster": {"image": {"x": 0.8125, "y": 0.0625}, "text": "毒桦栗树", "value": "default"}, "antliontribute": {"image": {"x": 0.125, "y": 0.0}, "text": "蚁狮贡品", "value": "default"}, "malbatross": {"image": {"x": 0.5, "y": 0.25}, "text": "邪天翁", "value": "default"}, "deerclops": {"image": {"x": 0.9375, "y": 0.0625}, "text": "独眼巨鹿", "value": "default"}, "dragonfly": {"image": {"x": 0.0, "y": 0.125}, "text": "龙蝇", "value": "default"}, "crabking": {"image": {"x": 0.4375, "y": 0.0625}, "text": "帝王蟹", "value": "default"}, "sharkboi": {"image": {"x": 0.5, "y": 0.4375}, "text": "大霜鲨", "value": "default"}, "beequeen": {"image": {"x": 0.625, "y": 0.0}, "text": "蜂王", "value": "default"}, "daywalker2": {"image": {"x": 0.75, "y": 0.0625}, "text": "拾荒疯猪", "value": "default"}, "spiderqueen": {"image": {"x": 0.9375, "y": 0.4375}, "text": "蜘蛛女王", "value": "default"}, "liefs": {"image": {"x": 0.9375, "y": 0.1875}, "text": "树精守卫", "value": "default"}, "fruitfly": {"image": {"x": 0.875, "y": 0.125}, "text": "果蝇王", "value": "default"}, "klaus": {"image": {"x": 0.75, "y": 0.1875}, "text": "克劳斯", "value": "default"}}}, "lunar_mutations": {"order": 9, "text": "月亮变异", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "default": "默认"}, "items": {"mutated_buzzard_gestalt": {"image": {"x": 0.625, "y": 0.3125}, "text": "水晶冠秃鹫", "value": "default"}, "mutated_birds": {"image": {"x": 0.5, "y": 0.3125}, "text": "变异的鸟", "value": "default"}, "penguins_moon": {"image": {"x": 0.0, "y": 0.3125}, "text": "永冻企鸥", "value": "default"}, "mutated_merm": {"image": {"x": 0.8125, "y": 0.3125}, "text": "变异鱼人", "value": "default"}, "mutated_spiderqueen": {"image": {"x": 0.875, "y": 0.3125}, "text": "破碎蜘蛛洞", "value": "default"}, "mutated_hounds": {"image": {"x": 0.75, "y": 0.3125}, "text": "恐怖猎犬", "value": "default"}, "mutated_warg": {"image": {"x": 0.9375, "y": 0.3125}, "text": "附身座狼", "value": "default"}, "mutated_bearger": {"image": {"x": 0.4375, "y": 0.3125}, "text": "装甲熊獾", "value": "default"}, "mutated_bird_gestalt": {"image": {"x": 0.5625, "y": 0.3125}, "text": "亮喙鸟", "value": "default"}, "mutated_deerclops": {"image": {"x": 0.6875, "y": 0.3125}, "text": "晶体独眼巨鹿", "value": "default"}, "moon_spider": {"image": {"x": 0.0625, "y": 0.3125}, "text": "破碎蜘蛛", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}}}, "animals": {"order": 6, "text": "生物", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "items": {"grassgekkos": {"image": {"x": 0.25, "y": 0.1875}, "text": "草壁虎转化", "value": "default"}, "wobsters": {"image": {"x": 0.1875, "y": 0.5625}, "text": "龙虾", "value": "default"}, "butterfly": {"image": {"x": 0.0625, "y": 0.0625}, "text": "蝴蝶", "value": "default"}, "rabbits_setting": {"image": {"x": 0.8125, "y": 0.375}, "text": "兔子", "value": "default"}, "bees_setting": {"image": {"x": 0.6875, "y": 0.0}, "text": "蜜蜂", "value": "default"}, "pigs_setting": {"image": {"x": 0.5, "y": 0.375}, "text": "猪", "value": "default"}, "gnarwail": {"image": {"x": 0.0625, "y": 0.1875}, "text": "一角鲸", "value": "default"}, "birds": {"image": {"x": 0.875, "y": 0.0}, "text": "鸟", "value": "default"}, "penguins": {"image": {"x": 0.25, "y": 0.375}, "text": "企鸥", "value": "default"}, "catcoons": {"image": {"x": 0.25, "y": 0.0625}, "text": "浣猫", "value": "default"}, "otters_setting": {"image": {"x": 0.0625, "y": 0.375}, "text": "水獭掠夺者", "value": "default"}, "fishschools": {"image": {"x": 0.5, "y": 0.125}, "text": "鱼群", "value": "default"}, "bunnymen_setting": {"image": {"x": 0.0, "y": 0.0625}, "text": "兔人", "value": "default"}, "perd": {"image": {"x": 0.3125, "y": 0.375}, "text": "火鸡", "value": "default"}, "moles_setting": {"image": {"x": 0.75, "y": 0.25}, "text": "鼹鼠", "value": "default"}}}, "portal_resources": {"order": 5, "text": "非自然传送门资源", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "items": {"lightcrab_portalrate": {"image": {"x": 0.0, "y": 0.25}, "text": "发光蟹", "value": "default"}, "monkeytail_portalrate": {"image": {"x": 0.9375, "y": 0.25}, "text": "猴尾草", "value": "default"}, "powder_monkey_portalrate": {"image": {"x": 0.75, "y": 0.375}, "text": "火药猴", "value": "default"}, "bananabush_portalrate": {"image": {"x": 0.3125, "y": 0.0}, "text": "香蕉丛", "value": "default"}, "portal_spawnrate": {"image": {"x": 0.8125, "y": 0.25}, "text": "传送频率", "value": "default"}, "palmcone_seed_portalrate": {"image": {"x": 0.1875, "y": 0.375}, "text": "棕榈松果树芽", "value": "default"}}}, "misc": {"order": 3, "text": "世界", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"lightning": {"image": {"x": 0.1875, "y": 0.25}, "text": "闪电", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "wanderingtrader_enabled": {"image": {"x": 0.8125, "y": 0.5}, "text": "流浪商人", "desc": {"none": "禁用", "always": "启用"}, "value": "always"}, "petrification": {"image": {"x": 0.4375, "y": 0.375}, "text": "森林石化", "desc": {"none": "无", "few": "慢", "default": "默认", "many": "快", "max": "极快"}, "value": "default"}, "hunt": {"image": {"x": 0.6875, "y": 0.5}, "text": "狩猎", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "frograin": {"image": {"x": 0.8125, "y": 0.125}, "text": "青蛙雨", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "hounds": {"image": {"x": 0.4375, "y": 0.1875}, "text": "猎犬袭击", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "order": 1, "value": "default"}, "alternatehunt": {"image": {"x": 0.0625, "y": 0.0}, "text": "狩猎惊喜", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "wildfires": {"image": {"x": 0.6875, "y": 0.4375}, "text": "野火", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "rifts_frequency": {"image": {"x": 0.25, "y": 0.25}, "text": "荒野裂隙频率", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "weather": {"image": {"x": 0.875, "y": 0.375}, "text": "雨", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "winterhounds": {"image": {"x": 0.0625, "y": 0.5625}, "text": "冰猎犬群", "desc": {"never": "无", "default": "默认"}, "order": 2, "value": "default"}, "lunarhail_frequency": {"image": {"x": 0.3125, "y": 0.25}, "text": "月雹", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "summerhounds": {"image": {"x": 0.5, "y": 0.5}, "text": "火猎犬群", "desc": {"never": "无", "default": "默认"}, "order": 3, "value": "default"}, "rifts_enabled": {"image": {"x": 0.25, "y": 0.25}, "text": "荒野裂隙", "desc": {"never": "无", "default": "自动检测", "always": "总是"}, "value": "default"}, "meteorshowers": {"image": {"x": 0.625, "y": 0.25}, "text": "流星频率", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}}}, "monsters": {"order": 7, "text": "敌对生物", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "items": {"mosquitos": {"image": {"x": 0.1875, "y": 0.3125}, "text": "蚊子", "value": "default"}, "cookiecutters": {"image": {"x": 0.375, "y": 0.0625}, "text": "饼干切割机", "value": "default"}, "spiders_setting": {"image": {"x": 0.0, "y": 0.5}, "text": "蜘蛛", "value": "default"}, "hound_mounds": {"image": {"x": 0.5, "y": 0.1875}, "text": "猎犬", "value": "default"}, "merms": {"image": {"x": 0.5625, "y": 0.25}, "text": "鱼人", "value": "default"}, "squid": {"image": {"x": 0.375, "y": 0.5}, "text": "鱿鱼", "value": "default"}, "lureplants": {"image": {"x": 0.375, "y": 0.25}, "text": "食人花", "value": "default"}, "pirateraids": {"image": {"x": 0.625, "y": 0.375}, "text": "月亮码头海盗", "value": "default"}, "bats_setting": {"image": {"x": 0.4375, "y": 0.0}, "text": "蝙蝠", "value": "default"}, "spider_warriors": {"image": {"x": 0.25, "y": 0.5}, "text": "蜘蛛战士", "desc": {"never": "无", "default": "默认"}, "value": "default"}, "walrus_setting": {"image": {"x": 0.4375, "y": 0.25}, "text": "海象", "value": "default"}, "sharks": {"image": {"x": 0.5625, "y": 0.4375}, "text": "鲨鱼", "value": "default"}, "wasps": {"image": {"x": 0.9375, "y": 0.5}, "text": "杀人蜂", "value": "default"}, "frogs": {"image": {"x": 0.75, "y": 0.125}, "text": "青蛙", "value": "default"}}}}}, "cave": {"WORLDGEN_GROUP": {"monsters": {"order": 5, "text": "敌对生物以及刷新点", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "items": {"spiders": {"image": {"x": 0.9375, "y": 0.375}, "text": "蜘蛛巢", "value": "default"}, "chess": {"image": {"x": 0.875, "y": 0.0}, "text": "发条装置", "value": "default"}, "tentacles": {"image": {"x": 0.1875, "y": 0.5}, "text": "触手", "value": "default"}, "fissure": {"image": {"x": 0.0, "y": 0.125}, "text": "梦魇裂隙", "value": "default"}, "cave_spiders": {"image": {"x": 0.8125, "y": 0.0}, "text": "蛛网岩", "value": "default"}, "worms": {"image": {"x": 0.9375, "y": 0.5}, "text": "洞穴蠕虫", "value": "default"}, "bats": {"image": {"x": 0.125, "y": 0.0}, "text": "蝙蝠", "value": "default"}}}, "resources": {"order": 3, "text": "资源", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "items": {"wormlights": {"image": {"x": 0.875, "y": 0.5}, "text": "发光浆果", "value": "default"}, "rock": {"image": {"x": 0.5, "y": 0.375}, "text": "巨石", "value": "default"}, "mushtree": {"image": {"x": 0.6875, "y": 0.25}, "text": "蘑菇树", "value": "default"}, "reeds": {"image": {"x": 0.375, "y": 0.375}, "text": "芦苇", "value": "default"}, "grass": {"image": {"x": 0.25, "y": 0.125}, "text": "草", "value": "default"}, "banana": {"image": {"x": 0.0625, "y": 0.0}, "text": "香蕉", "value": "default"}, "trees": {"image": {"x": 0.375, "y": 0.5}, "text": "树(所有)", "value": "default"}, "lichen": {"image": {"x": 0.5, "y": 0.125}, "text": "苔藓", "value": "default"}, "cave_ponds": {"image": {"x": 0.25, "y": 0.375}, "text": "池塘", "value": "default"}, "marshbush": {"image": {"x": 0.6875, "y": 0.125}, "text": "尖刺灌木", "value": "default"}, "fern": {"image": {"x": 0.9375, "y": 0.0}, "text": "洞穴蕨类", "value": "default"}, "mushroom": {"image": {"x": 0.625, "y": 0.25}, "text": "蘑菇", "value": "default"}, "flint": {"image": {"x": 0.0625, "y": 0.125}, "text": "燧石", "value": "default"}, "berrybush": {"image": {"x": 0.3125, "y": 0.0}, "text": "浆果丛", "value": "default"}, "flower_cave": {"image": {"x": 0.1875, "y": 0.125}, "text": "荧光花", "value": "default"}, "sapling": {"image": {"x": 0.625, "y": 0.375}, "text": "树苗", "value": "default"}}}, "animals": {"order": 4, "text": "生物以及刷新点", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "items": {"monkey": {"image": {"x": 0.875, "y": 0.125}, "text": "穴居猴桶", "value": "default"}, "slurtles": {"image": {"x": 0.875, "y": 0.375}, "text": "蛞蝓龟窝", "value": "default"}, "slurper": {"image": {"x": 0.8125, "y": 0.375}, "text": "啜食者", "value": "default"}, "bunnymen": {"image": {"x": 0.375, "y": 0.0}, "text": "兔屋", "value": "default"}, "rocky": {"image": {"x": 0.5625, "y": 0.375}, "text": "石虾", "value": "default"}}}, "misc": {"order": 2, "text": "世界", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": null, "items": {"prefabswaps_start": {"image": {"x": 0.0625, "y": 0.5}, "text": "开始资源多样化", "desc": {"classic": "经典", "default": "默认", "highly random": "非常随机"}, "order": 20, "value": "default"}, "task_set": {"image": {"x": 0.6875, "y": 0.5}, "text": "生物群系", "desc": {"cave_default": "地下"}, "order": 1, "value": "cave_default"}, "touchstone": {"image": {"x": 0.3125, "y": 0.5}, "text": "试金石", "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "order": 17, "value": "default"}, "world_size": {"image": {"x": 0.75, "y": 0.5}, "text": "世界大小", "desc": {"small": "小", "medium": "中", "default": "大", "huge": "巨大"}, "order": 3, "value": "default"}, "branching": {"image": {"x": 0.5625, "y": 0.5}, "text": "分支", "desc": {"never": "从不", "least": "最少", "default": "默认", "most": "最多", "random": "随机"}, "order": 4, "value": "default"}, "loop": {"image": {"x": 0.625, "y": 0.5}, "text": "环形", "desc": {"never": "从不", "default": "默认", "always": "总是"}, "order": 5, "value": "default"}, "start_location": {"image": {"x": 0.8125, "y": 0.5}, "text": "出生点", "desc": {"caves": "洞穴"}, "order": 2, "value": "caves"}, "cavelight": {"image": {"x": 0.75, "y": 0.0}, "text": "洞穴光照", "desc": {"never": "无", "veryslow": "极慢", "slow": "慢", "default": "默认", "fast": "快", "veryfast": "极快"}, "order": 18, "value": "default"}, "boons": {"image": {"x": 0.75, "y": 0.375}, "text": "失败的冒险家", "desc": {"never": "无", "rare": "很少", "uncommon": "较少", "default": "默认", "often": "较多", "mostly": "很多", "always": "大量", "insane": "疯狂"}, "order": 18, "value": "default"}}}}, "WORLDSETTINGS_GROUP": {"resources": {"order": 4, "text": "资源再生", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "veryslow": "极慢", "slow": "慢", "default": "默认", "fast": "快", "veryfast": "极快"}, "items": {"mushtree_regrowth": {"image": {"x": 0.3125, "y": 0.3125}, "text": "蘑菇树", "value": "default"}, "mushtree_moon_regrowth": {"image": {"x": 0.375, "y": 0.3125}, "text": "月亮蘑菇树", "value": "default"}, "flower_cave_regrowth": {"image": {"x": 0.6875, "y": 0.125}, "text": "荧光花", "value": "default"}, "lightflier_flower_regrowth": {"image": {"x": 0.125, "y": 0.25}, "text": "光虫花", "value": "default"}, "regrowth": {"image": {"x": 0.0, "y": 0.4375}, "text": "再生速度", "order": 1, "value": "default"}}}, "giants": {"order": 8, "text": "巨兽", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "items": {"toadstool": {"image": {"x": 0.625, "y": 0.5}, "text": "毒菌蟾蜍", "value": "default"}, "daywalker": {"image": {"x": 0.6875, "y": 0.0625}, "text": "梦魇疯猪", "value": "default"}, "spiderqueen": {"image": {"x": 0.9375, "y": 0.4375}, "text": "蜘蛛女王", "value": "default"}, "liefs": {"image": {"x": 0.9375, "y": 0.1875}, "text": "树精守卫", "value": "default"}, "fruitfly": {"image": {"x": 0.875, "y": 0.125}, "text": "果蝇王", "value": "default"}}}, "lunar_mutations": {"order": 9, "text": "月亮变异", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "default": "默认"}, "items": {"mutated_birds": {"image": {"x": 0.5, "y": 0.3125}, "text": "变异的鸟", "value": "default"}, "mutated_merm": {"image": {"x": 0.8125, "y": 0.3125}, "text": "变异鱼人", "value": "default"}, "mutated_spiderqueen": {"image": {"x": 0.875, "y": 0.3125}, "text": "破碎蜘蛛洞", "value": "default"}, "moon_spider": {"image": {"x": 0.0625, "y": 0.3125}, "text": "破碎蜘蛛", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}}}, "animals": {"order": 6, "text": "生物", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "items": {"grassgekkos": {"image": {"x": 0.25, "y": 0.1875}, "text": "草壁虎转化", "value": "default"}, "dustmoths": {"image": {"x": 0.125, "y": 0.125}, "text": "尘蛾", "value": "default"}, "pigs_setting": {"image": {"x": 0.5, "y": 0.375}, "text": "猪", "value": "default"}, "slurtles_setting": {"image": {"x": 0.625, "y": 0.4375}, "text": "蛞蝓龟", "value": "default"}, "mushgnome": {"image": {"x": 0.25, "y": 0.3125}, "text": "蘑菇地精", "value": "default"}, "monkey_setting": {"image": {"x": 0.875, "y": 0.25}, "text": "穴居猴", "value": "default"}, "lightfliers": {"image": {"x": 0.0625, "y": 0.25}, "text": "球状光虫", "value": "default"}, "rocky_setting": {"image": {"x": 0.125, "y": 0.4375}, "text": "石虾", "value": "default"}, "snurtles": {"image": {"x": 0.75, "y": 0.4375}, "text": "蜗牛龟", "value": "default"}, "bunnymen_setting": {"image": {"x": 0.0, "y": 0.0625}, "text": "兔人", "value": "default"}, "moles_setting": {"image": {"x": 0.75, "y": 0.25}, "text": "鼹鼠", "value": "default"}}}, "misc": {"order": 3, "text": "世界", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"rifts_frequency_cave": {"image": {"x": 0.4375, "y": 0.4375}, "text": "荒野裂隙频率", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "acidrain_enabled": {"image": {"x": 0.0, "y": 0.0}, "text": "酸雨", "desc": {"none": "禁用", "always": "启用"}, "value": "always"}, "rifts_enabled_cave": {"image": {"x": 0.4375, "y": 0.4375}, "text": "荒野裂隙", "desc": {"never": "无", "default": "自动检测", "always": "总是"}, "value": "default"}, "atriumgate": {"image": {"x": 0.1875, "y": 0.0}, "text": "远古大门", "desc": {"veryslow": "极慢", "slow": "慢", "default": "默认", "fast": "快", "veryfast": "极快"}, "value": "default"}, "wormattacks_boss": {"image": {"x": 0.3125, "y": 0.5625}, "text": "大蠕虫", "desc": {"never": "从不", "rare": "稀有", "default": "默认", "often": "常见", "always": "总是"}, "value": "default"}, "wormattacks": {"image": {"x": 0.25, "y": 0.5625}, "text": "洞穴蠕虫袭击", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "earthquakes": {"image": {"x": 0.1875, "y": 0.125}, "text": "地震", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}, "weather": {"image": {"x": 0.875, "y": 0.375}, "text": "雨", "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "value": "default"}}}, "monsters": {"order": 7, "text": "敌对生物", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "无", "rare": "很少", "default": "默认", "often": "较多", "always": "大量"}, "items": {"chest_mimics": {"image": {"x": 0.3125, "y": 0.0625}, "text": "暴躁箱子", "value": "default"}, "spiders_setting": {"image": {"x": 0.0, "y": 0.5}, "text": "蜘蛛", "value": "default"}, "spider_spitter": {"image": {"x": 0.1875, "y": 0.5}, "text": "喷射蜘蛛", "value": "default"}, "merms": {"image": {"x": 0.5625, "y": 0.25}, "text": "鱼人", "value": "default"}, "bats_setting": {"image": {"x": 0.4375, "y": 0.0}, "text": "蝙蝠", "value": "default"}, "spider_warriors": {"image": {"x": 0.25, "y": 0.5}, "text": "蜘蛛战士", "desc": {"never": "无", "default": "默认"}, "value": "default"}, "spider_dropper": {"image": {"x": 0.0625, "y": 0.5}, "text": "穴居悬蛛", "value": "default"}, "spider_hider": {"image": {"x": 0.125, "y": 0.5}, "text": "洞穴蜘蛛", "value": "default"}, "nightmarecreatures": {"image": {"x": 0.0, "y": 0.375}, "text": "遗迹梦魇", "value": "default"}, "molebats": {"image": {"x": 0.6875, "y": 0.25}, "text": "裸鼹蝠", "value": "default"}, "itemmimics": {"image": {"x": 0.6875, "y": 0.1875}, "text": "拟态蠕虫", "value": "default"}}}}}}, "en": {"forest": {"WORLDGEN_GROUP": {"monsters": {"order": 5, "text": "Hostile Creatures and Spawners", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "items": {"spiders": {"image": {"x": 0.9375, "y": 0.375}, "text": "Spider Dens", "value": "default"}, "angrybees": {"image": {"x": 0.5, "y": 0.5}, "text": "Killer Bee Hives", "value": "default"}, "chess": {"image": {"x": 0.875, "y": 0.0}, "text": "Clockworks", "value": "default"}, "tentacles": {"image": {"x": 0.1875, "y": 0.5}, "text": "Tentacles", "value": "default"}, "walrus": {"image": {"x": 0.625, "y": 0.125}, "text": "MacTusk Camps", "value": "default"}, "ocean_waterplant": {"image": {"x": 0.0, "y": 0.375}, "text": "Sea Weeds", "desc": {"ocean_never": "None", "ocean_rare": "Little", "ocean_uncommon": "Less", "ocean_default": "Default", "ocean_often": "More", "ocean_mostly": "Lots", "ocean_always": "Tons", "ocean_insane": "Insane"}, "value": "ocean_default"}, "tallbirds": {"image": {"x": 0.125, "y": 0.5}, "text": "Tallbirds", "value": "default"}, "moon_spiders": {"image": {"x": 0.4375, "y": 0.25}, "text": "Shattered Spider Holes", "value": "default"}, "houndmound": {"image": {"x": 0.3125, "y": 0.125}, "text": "Hound Mounds", "value": "default"}, "merm": {"image": {"x": 0.75, "y": 0.125}, "text": "Leaky Shack", "value": "default"}}}, "resources": {"order": 3, "text": "Resources", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "items": {"moon_starfish": {"image": {"x": 0.5, "y": 0.25}, "text": "Anenemies", "value": "default"}, "rock_ice": {"image": {"x": 0.375, "y": 0.125}, "text": "Mini Glaciers", "value": "default"}, "moon_sapling": {"image": {"x": 0.375, "y": 0.25}, "text": "Lunar Saplings", "value": "default"}, "rock": {"image": {"x": 0.5, "y": 0.375}, "text": "Boulders", "value": "default"}, "moon_tree": {"image": {"x": 0.5625, "y": 0.25}, "text": "Lune Trees", "value": "default"}, "reeds": {"image": {"x": 0.375, "y": 0.375}, "text": "Reeds", "value": "default"}, "cactus": {"image": {"x": 0.5625, "y": 0.0}, "text": "Cacti", "value": "default"}, "grass": {"image": {"x": 0.25, "y": 0.125}, "text": "Grass", "value": "default"}, "palmconetree": {"image": {"x": 0.125, "y": 0.375}, "text": "Palmcone Tree", "value": "default"}, "ponds": {"image": {"x": 0.25, "y": 0.375}, "text": "Ponds", "value": "default"}, "flowers": {"image": {"x": 0.125, "y": 0.125}, "text": "Flowers, Evil Flowers", "value": "default"}, "ocean_bullkelp": {"image": {"x": 0.75, "y": 0.25}, "text": "Bull Kelp", "value": "default"}, "trees": {"image": {"x": 0.375, "y": 0.5}, "text": "Trees (All)", "value": "default"}, "moon_hotspring": {"image": {"x": 0.25, "y": 0.25}, "text": "Hot Springs", "value": "default"}, "marshbush": {"image": {"x": 0.6875, "y": 0.125}, "text": "Spiky Bushes", "value": "default"}, "ocean_seastack": {"image": {"x": 0.875, "y": 0.25}, "text": "Sea Stacks", "desc": {"ocean_never": "None", "ocean_rare": "Little", "ocean_uncommon": "Less", "ocean_default": "Default", "ocean_often": "More", "ocean_mostly": "Lots", "ocean_always": "Tons", "ocean_insane": "Insane"}, "value": "ocean_default"}, "tumbleweed": {"image": {"x": 0.4375, "y": 0.5}, "text": "Tumbleweeds", "value": "default"}, "moon_berrybush": {"image": {"x": 0.9375, "y": 0.125}, "text": "Stone Fruit Bushes", "value": "default"}, "moon_bullkelp": {"image": {"x": 0.0, "y": 0.25}, "text": "Beached Bull Kelp", "value": "default"}, "mushroom": {"image": {"x": 0.625, "y": 0.25}, "text": "Mushrooms", "value": "default"}, "moon_rock": {"image": {"x": 0.3125, "y": 0.25}, "text": "Lunar Rocks", "value": "default"}, "carrot": {"image": {"x": 0.625, "y": 0.0}, "text": "Carrots", "value": "default"}, "flint": {"image": {"x": 0.0625, "y": 0.125}, "text": "Flint", "value": "default"}, "berrybush": {"image": {"x": 0.3125, "y": 0.0}, "text": "Berry Bushes", "value": "default"}, "meteorspawner": {"image": {"x": 0.4375, "y": 0.0}, "text": "Meteor Fields", "value": "default"}, "sapling": {"image": {"x": 0.625, "y": 0.375}, "text": "Saplings", "value": "default"}}}, "animals": {"order": 4, "text": "Creatures and Spawners", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "items": {"ocean_shoal": {"image": {"x": 0.9375, "y": 0.25}, "text": "Shoals", "value": "default"}, "moon_fruitdragon": {"image": {"x": 0.1875, "y": 0.25}, "text": "Saladmander", "value": "default"}, "rabbits": {"image": {"x": 0.3125, "y": 0.375}, "text": "Rabbit Holes", "value": "default"}, "catcoon": {"image": {"x": 0.6875, "y": 0.0}, "text": "Hollow Stump", "value": "default"}, "ocean_otterdens": {"image": {"x": 0.8125, "y": 0.25}, "text": "Marotter Dens", "value": "default"}, "ocean_wobsterden": {"image": {"x": 0.0625, "y": 0.375}, "text": "Wobster Mounds", "value": "default"}, "moles": {"image": {"x": 0.8125, "y": 0.125}, "text": "Mole Burrows", "value": "default"}, "buzzard": {"image": {"x": 0.5, "y": 0.0}, "text": "Buzzards", "value": "default"}, "moon_carrot": {"image": {"x": 0.0625, "y": 0.25}, "text": "Carrats", "value": "default"}, "pigs": {"image": {"x": 0.1875, "y": 0.375}, "text": "Pig Houses", "value": "default"}, "lightninggoat": {"image": {"x": 0.5625, "y": 0.125}, "text": "Volt Goats", "value": "default"}, "beefalo": {"image": {"x": 0.1875, "y": 0.0}, "text": "Beefalos", "value": "default"}, "bees": {"image": {"x": 0.25, "y": 0.0}, "text": "Bee Hives", "value": "default"}}}, "misc": {"order": 2, "text": "World", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": null, "items": {"terrariumchest": {"image": {"x": 0.25, "y": 0.5}, "text": "Terrarium", "desc": {"never": "None", "default": "Default"}, "value": "default"}, "prefabswaps_start": {"image": {"x": 0.0625, "y": 0.5}, "text": "Starting Resource Variety", "desc": {"classic": "Classic", "default": "Default", "highly random": "Highly Random"}, "order": 20, "value": "default"}, "stageplays": {"image": {"x": 0.0, "y": 0.5}, "text": "Stage Plays", "desc": {"never": "None", "default": "Default"}, "value": "default"}, "task_set": {"image": {"x": 0.6875, "y": 0.5}, "text": "Biomes", "desc": {"default": "Together", "classic": "Classic"}, "order": 1, "value": "default"}, "touchstone": {"image": {"x": 0.3125, "y": 0.5}, "text": "Touch Stones", "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "order": 17, "value": "default"}, "world_size": {"image": {"x": 0.75, "y": 0.5}, "text": "World Size", "desc": {"small": "Small", "medium": "Medium", "default": "Large", "huge": "Huge"}, "order": 3, "value": "default"}, "balatro": {"image": {"x": 0.0, "y": 0.0}, "text": "JIMBO", "desc": {"never": "None", "default": "Default"}, "value": "default"}, "junkyard": {"image": {"x": 0.4375, "y": 0.125}, "text": "Junk Yard", "desc": {"never": "None", "default": "Default"}, "value": "default"}, "branching": {"image": {"x": 0.5625, "y": 0.5}, "text": "Branches", "desc": {"never": "Never", "least": "Least", "default": "Default", "most": "Most", "random": "Random"}, "order": 4, "value": "default"}, "loop": {"image": {"x": 0.625, "y": 0.5}, "text": "Loops", "desc": {"never": "Never", "default": "Default", "always": "Always"}, "order": 5, "value": "default"}, "start_location": {"image": {"x": 0.8125, "y": 0.5}, "text": "Spawn Area", "desc": {"darkness": "Dark", "default": "Default", "plus": "Plus"}, "order": 2, "value": "default"}, "moon_fissure": {"image": {"x": 0.125, "y": 0.25}, "text": "Celestial Fissures", "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "value": "default"}, "roads": {"image": {"x": 0.4375, "y": 0.375}, "text": "Roads", "desc": {"never": "None", "default": "Default"}, "order": 6, "value": "default"}, "boons": {"image": {"x": 0.75, "y": 0.375}, "text": "Failed Survivors", "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "order": 18, "value": "default"}}}, "global": {"order": 1, "text": "Global", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": null, "items": {"season_start": {"image": {"x": 0.6875, "y": 0.375}, "text": "Starting Season", "desc": {"default": "Autumn", "winter": "Winter", "spring": "Spring", "summer": "Summer", "autumn|spring": "Autumn or Spring", "winter|summer": "Winter or Summer", "autumn|winter|spring|summer": "Random"}, "order": 1, "value": "default"}}}}, "WORLDSETTINGS_GROUP": {"survivors": {"order": 2, "text": "Survivors", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"healthpenalty": {"image": {"x": 0.375, "y": 0.1875}, "text": "Max Health Penalty", "desc": {"none": "Disabled", "always": "Enabled"}, "order": 5, "value": "always"}, "extrastartingitems": {"image": {"x": 0.375, "y": 0.125}, "text": "Extra Starting Resources", "desc": {"0": "Always", "5": "After Day 5", "default": "After Day 10", "15": "After Day 15", "20": "After Day 20", "none": "Never"}, "order": 1, "value": "default"}, "spawnprotection": {"image": {"x": 0.875, "y": 0.4375}, "text": "Griefer Spawn Protection", "desc": {"never": "None", "default": "Auto Detect", "always": "Always"}, "order": 3, "value": "default"}, "temperaturedamage": {"image": {"x": 0.5625, "y": 0.5}, "text": "Temperature Damage", "desc": {"nonlethal": "Nonlethal", "default": "Default"}, "order": 7, "value": "default"}, "shadowcreatures": {"image": {"x": 0.375, "y": 0.4375}, "text": "Sanity Monsters", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "order": 10, "value": "default"}, "darkness": {"image": {"x": 0.5625, "y": 0.0625}, "text": "Darkness Damage", "desc": {"nonlethal": "Nonlethal", "default": "Default"}, "order": 9, "value": "default"}, "seasonalstartingitems": {"image": {"x": 0.3125, "y": 0.4375}, "text": "Seasonal Starting Items", "desc": {"never": "None", "default": "Default"}, "order": 2, "value": "default"}, "dropeverythingondespawn": {"image": {"x": 0.0625, "y": 0.125}, "text": "Drop Items on Disconnect", "desc": {"default": "Default", "always": "Everything"}, "order": 4, "value": "default"}, "brightmarecreatures": {"image": {"x": 0.9375, "y": 0.0}, "text": "Enlightenment Monsters", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "order": 11, "value": "default"}, "hunger": {"image": {"x": 0.5625, "y": 0.1875}, "text": "Hunger Damage", "desc": {"nonlethal": "Nonlethal", "default": "Default"}, "order": 8, "value": "default"}, "lessdamagetaken": {"image": {"x": 0.875, "y": 0.1875}, "text": "Damage Taken", "desc": {"always": "Less", "none": "Default", "more": "More"}, "order": 6, "value": "none"}}}, "global": {"order": 0, "text": "Global", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"specialevent": {"image": {"x": 0.25, "y": 0.125}, "text": "Events", "desc": {"none": "None", "default": "Auto"}, "order": 1, "value": "default"}, "ghostenabled": {"image": {"x": 0.9375, "y": 0.125}, "text": "Survivor Death", "desc": {"none": "Change Survivor", "always": "Become a Ghost"}, "order": 8, "value": "always"}, "spawnmode": {"image": {"x": 0.8125, "y": 0.4375}, "text": "Spawn Mode", "desc": {"fixed": "Florid Postern", "scatter": "Random"}, "order": 7, "value": "fixed"}, "portalresurection": {"image": {"x": 0.6875, "y": 0.375}, "text": "Revive At Florid Postern", "desc": {"none": "Disabled", "always": "Enabled"}, "order": 9, "value": "none"}, "autumn": {"image": {"x": 0.25, "y": 0.0}, "text": "Autumn", "desc": {"noseason": "None", "veryshortseason": "Very Short", "shortseason": "Short", "default": "Default", "longseason": "Long", "verylongseason": "Very Long", "random": "Random"}, "order": 2, "value": "default"}, "winter": {"image": {"x": 0.0, "y": 0.5625}, "text": "Winter", "desc": {"noseason": "None", "veryshortseason": "Very Short", "shortseason": "Short", "default": "Default", "longseason": "Long", "verylongseason": "Very Long", "random": "Random"}, "order": 3, "value": "default"}, "krampus": {"image": {"x": 0.8125, "y": 0.1875}, "text": "Krampii", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "order": 13, "value": "default"}, "beefaloheat": {"image": {"x": 0.5625, "y": 0.0}, "text": "Beefalo Mating Frequency", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "order": 12, "value": "default"}, "spring": {"image": {"x": 0.3125, "y": 0.5}, "text": "Spring", "desc": {"noseason": "None", "veryshortseason": "Very Short", "shortseason": "Short", "default": "Default", "longseason": "Long", "verylongseason": "Very Long", "random": "Random"}, "order": 4, "value": "default"}, "ghostsanitydrain": {"image": {"x": 0.0, "y": 0.1875}, "text": "Ghost Sanity Drain", "desc": {"none": "Disabled", "always": "Enabled"}, "order": 10, "value": "always"}, "summer": {"image": {"x": 0.4375, "y": 0.5}, "text": "Summer", "desc": {"noseason": "None", "veryshortseason": "Very Short", "shortseason": "Short", "default": "Default", "longseason": "Long", "verylongseason": "Very Long", "random": "Random"}, "order": 5, "value": "default"}, "resettime": {"image": {"x": 0.0625, "y": 0.4375}, "text": "Death Reset Timer", "desc": {"none": "Disabled", "slow": "Slow", "default": "Default", "fast": "Fast", "always": "Instant"}, "order": 11, "value": "default"}, "day": {"image": {"x": 0.625, "y": 0.0625}, "text": "Day Type", "desc": {"default": "Default", "longday": "Long Day", "longdusk": "Long Dusk", "longnight": "Long Night", "noday": "No Day", "nodusk": "No Dusk", "nonight": "No Night", "onlyday": "Only Day", "onlydusk": "Only Dusk", "onlynight": "Only Night"}, "order": 6, "value": "default"}}}, "resources": {"order": 4, "text": "Resource Regrowth", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "veryslow": "Very Slow", "slow": "Slow", "default": "Default", "fast": "Fast", "veryfast": "Very Fast"}, "items": {"carrots_regrowth": {"image": {"x": 0.1875, "y": 0.0625}, "text": "Carrots", "value": "default"}, "basicresource_regrowth": {"image": {"x": 0.375, "y": 0.0}, "text": "Basic Resources", "desc": {"none": "Disabled", "always": "Enabled"}, "value": "none"}, "cactus_regrowth": {"image": {"x": 0.125, "y": 0.0625}, "text": "Cacti", "value": "default"}, "deciduoustree_regrowth": {"image": {"x": 0.875, "y": 0.0625}, "text": "Birchnut Trees", "value": "default"}, "palmconetree_regrowth": {"image": {"x": 0.125, "y": 0.375}, "text": "Palmcone Tree", "value": "default"}, "flowers_regrowth": {"image": {"x": 0.625, "y": 0.125}, "text": "Flowers", "value": "default"}, "twiggytrees_regrowth": {"image": {"x": 0.75, "y": 0.5}, "text": "Twiggy Trees", "value": "default"}, "regrowth": {"image": {"x": 0.0, "y": 0.4375}, "text": "Regrowth Multiplier", "order": 1, "value": "default"}, "moon_tree_regrowth": {"image": {"x": 0.125, "y": 0.3125}, "text": "Lune Trees", "value": "default"}, "reeds_regrowth": {"image": {"x": 0.9375, "y": 0.375}, "text": "Reeds", "value": "default"}, "saltstack_regrowth": {"image": {"x": 0.1875, "y": 0.4375}, "text": "Salt Formations", "value": "default"}, "evergreen_regrowth": {"image": {"x": 0.3125, "y": 0.125}, "text": "Evergreens", "value": "default"}}}, "events": {"order": 1, "text": "Events", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"default": "Default", "enabled": "Always"}, "items": {"hallowed_nights": {"image": {"x": 0.3125, "y": 0.1875}, "text": "Hallowed Nights", "order": 2, "value": "default"}, "year_of_the_catcoon": {"image": {"x": 0.6875, "y": 0.5625}, "text": "Year of the Catcoon", "order": 9, "value": "default"}, "year_of_the_gobbler": {"image": {"x": 0.375, "y": 0.375}, "text": "Year of the Gobbler", "order": 4, "value": "default"}, "year_of_the_carrat": {"image": {"x": 0.4375, "y": 0.5625}, "text": "Year of the Carrat", "order": 7, "value": "default"}, "year_of_the_snake": {"image": {"x": 0.625, "y": 0.5625}, "text": "Year of the Depths Worm", "order": 12, "value": "default"}, "crow_carnival": {"image": {"x": 0.5, "y": 0.0625}, "text": "Midsummer Cawnival", "order": 1, "value": "default"}, "year_of_the_bunnyman": {"image": {"x": 0.5625, "y": 0.5625}, "text": "Year of the Bunnyman", "order": 10, "value": "default"}, "year_of_the_pig": {"image": {"x": 0.5625, "y": 0.375}, "text": "Year of the Pig King", "order": 6, "value": "default"}, "year_of_the_varg": {"image": {"x": 0.875, "y": 0.5}, "text": "Year of the Varg", "order": 5, "value": "default"}, "year_of_the_beefalo": {"image": {"x": 0.375, "y": 0.5625}, "text": "Year of the Beefalo", "order": 8, "value": "default"}, "year_of_the_dragonfly": {"image": {"x": 0.5, "y": 0.5625}, "text": "Year of the Dragonfly", "order": 11, "value": "default"}, "winters_feast": {"image": {"x": 0.125, "y": 0.5625}, "text": "Winter's Feast", "order": 3, "value": "default"}}}, "giants": {"order": 8, "text": "Giants", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "items": {"goosemoose": {"image": {"x": 0.125, "y": 0.1875}, "text": "Meese/Geese", "value": "default"}, "eyeofterror": {"image": {"x": 0.4375, "y": 0.125}, "text": "Eye of Terror", "value": "default"}, "bearger": {"image": {"x": 0.5, "y": 0.0}, "text": "Bearger", "value": "default"}, "deciduousmonster": {"image": {"x": 0.8125, "y": 0.0625}, "text": "Poison Birchnut Trees", "value": "default"}, "antliontribute": {"image": {"x": 0.125, "y": 0.0}, "text": "Antlion Tribute", "value": "default"}, "malbatross": {"image": {"x": 0.5, "y": 0.25}, "text": "Malbatross", "value": "default"}, "deerclops": {"image": {"x": 0.9375, "y": 0.0625}, "text": "Deerclops", "value": "default"}, "dragonfly": {"image": {"x": 0.0, "y": 0.125}, "text": "Dragonfly", "value": "default"}, "crabking": {"image": {"x": 0.4375, "y": 0.0625}, "text": "Crabking", "value": "default"}, "sharkboi": {"image": {"x": 0.5, "y": 0.4375}, "text": "Frostjaw", "value": "default"}, "beequeen": {"image": {"x": 0.625, "y": 0.0}, "text": "Bee Queen", "value": "default"}, "daywalker2": {"image": {"x": 0.75, "y": 0.0625}, "text": "Scrappy Werepig", "value": "default"}, "spiderqueen": {"image": {"x": 0.9375, "y": 0.4375}, "text": "Spider Queen", "value": "default"}, "liefs": {"image": {"x": 0.9375, "y": 0.1875}, "text": "Treeguards", "value": "default"}, "fruitfly": {"image": {"x": 0.875, "y": 0.125}, "text": "Lord of the Fruit Flies", "value": "default"}, "klaus": {"image": {"x": 0.75, "y": 0.1875}, "text": "Klaus", "value": "default"}}}, "lunar_mutations": {"order": 9, "text": "Lunar Mutations", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "default": "Default"}, "items": {"mutated_buzzard_gestalt": {"image": {"x": 0.625, "y": 0.3125}, "text": "Crystal-Crested Buzzards", "value": "default"}, "mutated_birds": {"image": {"x": 0.5, "y": 0.3125}, "text": "Mutated Birds", "value": "default"}, "penguins_moon": {"image": {"x": 0.0, "y": 0.3125}, "text": "Permafrost Pengulls", "value": "default"}, "mutated_merm": {"image": {"x": 0.8125, "y": 0.3125}, "text": "Mutated Merms", "value": "default"}, "mutated_spiderqueen": {"image": {"x": 0.875, "y": 0.3125}, "text": "Shattered Spider Holes", "value": "default"}, "mutated_hounds": {"image": {"x": 0.75, "y": 0.3125}, "text": "Horror Hounds", "value": "default"}, "mutated_warg": {"image": {"x": 0.9375, "y": 0.3125}, "text": "Possessed Vargs", "value": "default"}, "mutated_bearger": {"image": {"x": 0.4375, "y": 0.3125}, "text": "Armored Bearger", "value": "default"}, "mutated_bird_gestalt": {"image": {"x": 0.5625, "y": 0.3125}, "text": "Bright-Beaked Birds", "value": "default"}, "mutated_deerclops": {"image": {"x": 0.6875, "y": 0.3125}, "text": "Crystal Deerclops", "value": "default"}, "moon_spider": {"image": {"x": 0.0625, "y": 0.3125}, "text": "Shattered Spiders", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}}}, "animals": {"order": 6, "text": "Creatures", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "items": {"grassgekkos": {"image": {"x": 0.25, "y": 0.1875}, "text": "Grass Gekko Morphing", "value": "default"}, "wobsters": {"image": {"x": 0.1875, "y": 0.5625}, "text": "Wobsters", "value": "default"}, "butterfly": {"image": {"x": 0.0625, "y": 0.0625}, "text": "Butterflies", "value": "default"}, "rabbits_setting": {"image": {"x": 0.8125, "y": 0.375}, "text": "Rabbits", "value": "default"}, "bees_setting": {"image": {"x": 0.6875, "y": 0.0}, "text": "Bees", "value": "default"}, "pigs_setting": {"image": {"x": 0.5, "y": 0.375}, "text": "Pigs", "value": "default"}, "gnarwail": {"image": {"x": 0.0625, "y": 0.1875}, "text": "Gnarwails", "value": "default"}, "birds": {"image": {"x": 0.875, "y": 0.0}, "text": "Birds", "value": "default"}, "penguins": {"image": {"x": 0.25, "y": 0.375}, "text": "Pengulls", "value": "default"}, "catcoons": {"image": {"x": 0.25, "y": 0.0625}, "text": "Catcoons", "value": "default"}, "otters_setting": {"image": {"x": 0.0625, "y": 0.375}, "text": "Marotters", "value": "default"}, "fishschools": {"image": {"x": 0.5, "y": 0.125}, "text": "Schools of Fish", "value": "default"}, "bunnymen_setting": {"image": {"x": 0.0, "y": 0.0625}, "text": "Bunnymen", "value": "default"}, "perd": {"image": {"x": 0.3125, "y": 0.375}, "text": "Gobblers", "value": "default"}, "moles_setting": {"image": {"x": 0.75, "y": 0.25}, "text": "Moles", "value": "default"}}}, "portal_resources": {"order": 5, "text": "Unnatural Portal Resources", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "items": {"lightcrab_portalrate": {"image": {"x": 0.0, "y": 0.25}, "text": "Crustashines", "value": "default"}, "monkeytail_portalrate": {"image": {"x": 0.9375, "y": 0.25}, "text": "Monkeytails", "value": "default"}, "powder_monkey_portalrate": {"image": {"x": 0.75, "y": 0.375}, "text": "Powder Monkeys", "value": "default"}, "bananabush_portalrate": {"image": {"x": 0.3125, "y": 0.0}, "text": "Banana Bushes", "value": "default"}, "portal_spawnrate": {"image": {"x": 0.8125, "y": 0.25}, "text": "Portal Activity", "value": "default"}, "palmcone_seed_portalrate": {"image": {"x": 0.1875, "y": 0.375}, "text": "Palmcone Sprouts", "value": "default"}}}, "misc": {"order": 3, "text": "World", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"lightning": {"image": {"x": 0.1875, "y": 0.25}, "text": "Lightning", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "wanderingtrader_enabled": {"image": {"x": 0.8125, "y": 0.5}, "text": "Wandering Trader", "desc": {"none": "Disabled", "always": "Enabled"}, "value": "always"}, "petrification": {"image": {"x": 0.4375, "y": 0.375}, "text": "Forest Petrification", "desc": {"none": "None", "few": "Slow", "default": "Default", "many": "Fast", "max": "Very Fast"}, "value": "default"}, "hunt": {"image": {"x": 0.6875, "y": 0.5}, "text": "Hunts", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "frograin": {"image": {"x": 0.8125, "y": 0.125}, "text": "Frog Rain", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "hounds": {"image": {"x": 0.4375, "y": 0.1875}, "text": "Hound Attacks", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "order": 1, "value": "default"}, "alternatehunt": {"image": {"x": 0.0625, "y": 0.0}, "text": "Hunt Surprises", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "wildfires": {"image": {"x": 0.6875, "y": 0.4375}, "text": "Wildfires", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "rifts_frequency": {"image": {"x": 0.25, "y": 0.25}, "text": "Wild Rift Frequency", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "weather": {"image": {"x": 0.875, "y": 0.375}, "text": "Rain", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "winterhounds": {"image": {"x": 0.0625, "y": 0.5625}, "text": "Ice Hound Waves", "desc": {"never": "None", "default": "Default"}, "order": 2, "value": "default"}, "lunarhail_frequency": {"image": {"x": 0.3125, "y": 0.25}, "text": "Lunar Hail", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "summerhounds": {"image": {"x": 0.5, "y": 0.5}, "text": "Fire Hound Waves", "desc": {"never": "None", "default": "Default"}, "order": 3, "value": "default"}, "rifts_enabled": {"image": {"x": 0.25, "y": 0.25}, "text": "Wild Rifts", "desc": {"never": "None", "default": "Auto Detect", "always": "Always"}, "value": "default"}, "meteorshowers": {"image": {"x": 0.625, "y": 0.25}, "text": "Meteor Frequency", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}}}, "monsters": {"order": 7, "text": "Hostile Creatures", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "items": {"mosquitos": {"image": {"x": 0.1875, "y": 0.3125}, "text": "Mosquitos", "value": "default"}, "cookiecutters": {"image": {"x": 0.375, "y": 0.0625}, "text": "Cookie Cutters", "value": "default"}, "spiders_setting": {"image": {"x": 0.0, "y": 0.5}, "text": "Spiders", "value": "default"}, "hound_mounds": {"image": {"x": 0.5, "y": 0.1875}, "text": "Hounds", "value": "default"}, "merms": {"image": {"x": 0.5625, "y": 0.25}, "text": "Merms", "value": "default"}, "squid": {"image": {"x": 0.375, "y": 0.5}, "text": "Skittersquids", "value": "default"}, "lureplants": {"image": {"x": 0.375, "y": 0.25}, "text": "Lureplants", "value": "default"}, "pirateraids": {"image": {"x": 0.625, "y": 0.375}, "text": "Moon Quay Pirates", "value": "default"}, "bats_setting": {"image": {"x": 0.4375, "y": 0.0}, "text": "Bats", "value": "default"}, "spider_warriors": {"image": {"x": 0.25, "y": 0.5}, "text": "Spider Warriors", "desc": {"never": "None", "default": "Default"}, "value": "default"}, "walrus_setting": {"image": {"x": 0.4375, "y": 0.25}, "text": "MacTusk", "value": "default"}, "sharks": {"image": {"x": 0.5625, "y": 0.4375}, "text": "Sharks", "value": "default"}, "wasps": {"image": {"x": 0.9375, "y": 0.5}, "text": "Killer Bees", "value": "default"}, "frogs": {"image": {"x": 0.75, "y": 0.125}, "text": "Frogs", "value": "default"}}}}}, "cave": {"WORLDGEN_GROUP": {"monsters": {"order": 5, "text": "Hostile Creatures and Spawners", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "items": {"spiders": {"image": {"x": 0.9375, "y": 0.375}, "text": "Spider Dens", "value": "default"}, "chess": {"image": {"x": 0.875, "y": 0.0}, "text": "Clockworks", "value": "default"}, "tentacles": {"image": {"x": 0.1875, "y": 0.5}, "text": "Tentacles", "value": "default"}, "fissure": {"image": {"x": 0.0, "y": 0.125}, "text": "Nightmare Fissures", "value": "default"}, "cave_spiders": {"image": {"x": 0.8125, "y": 0.0}, "text": "Spilagmites", "value": "default"}, "worms": {"image": {"x": 0.9375, "y": 0.5}, "text": "Cave Worms", "value": "default"}, "bats": {"image": {"x": 0.125, "y": 0.0}, "text": "Bats", "value": "default"}}}, "resources": {"order": 3, "text": "Resources", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "items": {"wormlights": {"image": {"x": 0.875, "y": 0.5}, "text": "Glow Berries", "value": "default"}, "rock": {"image": {"x": 0.5, "y": 0.375}, "text": "Boulders", "value": "default"}, "mushtree": {"image": {"x": 0.6875, "y": 0.25}, "text": "Mushroom Trees", "value": "default"}, "reeds": {"image": {"x": 0.375, "y": 0.375}, "text": "Reeds", "value": "default"}, "grass": {"image": {"x": 0.25, "y": 0.125}, "text": "Grass", "value": "default"}, "banana": {"image": {"x": 0.0625, "y": 0.0}, "text": "Bananas", "value": "default"}, "trees": {"image": {"x": 0.375, "y": 0.5}, "text": "Trees (All)", "value": "default"}, "lichen": {"image": {"x": 0.5, "y": 0.125}, "text": "Lichen", "value": "default"}, "cave_ponds": {"image": {"x": 0.25, "y": 0.375}, "text": "Ponds", "value": "default"}, "marshbush": {"image": {"x": 0.6875, "y": 0.125}, "text": "Spiky Bushes", "value": "default"}, "fern": {"image": {"x": 0.9375, "y": 0.0}, "text": "Cave Ferns", "value": "default"}, "mushroom": {"image": {"x": 0.625, "y": 0.25}, "text": "Mushrooms", "value": "default"}, "flint": {"image": {"x": 0.0625, "y": 0.125}, "text": "Flint", "value": "default"}, "berrybush": {"image": {"x": 0.3125, "y": 0.0}, "text": "Berry Bushes", "value": "default"}, "flower_cave": {"image": {"x": 0.1875, "y": 0.125}, "text": "Light Flowers", "value": "default"}, "sapling": {"image": {"x": 0.625, "y": 0.375}, "text": "Saplings", "value": "default"}}}, "animals": {"order": 4, "text": "Creatures and Spawners", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "items": {"monkey": {"image": {"x": 0.875, "y": 0.125}, "text": "Splumonkey Pods", "value": "default"}, "slurtles": {"image": {"x": 0.875, "y": 0.375}, "text": "Slurtle Mounds", "value": "default"}, "slurper": {"image": {"x": 0.8125, "y": 0.375}, "text": "Slurpers", "value": "default"}, "bunnymen": {"image": {"x": 0.375, "y": 0.0}, "text": "Rabbit Hutches", "value": "default"}, "rocky": {"image": {"x": 0.5625, "y": 0.375}, "text": "Rock Lobsters", "value": "default"}}}, "misc": {"order": 2, "text": "World", "atlas": {"name": "worldgen_customization", "width": 2048, "height": 1024, "item_size": 128}, "desc": null, "items": {"prefabswaps_start": {"image": {"x": 0.0625, "y": 0.5}, "text": "Starting Resource Variety", "desc": {"classic": "Classic", "default": "Default", "highly random": "Highly Random"}, "order": 20, "value": "default"}, "task_set": {"image": {"x": 0.6875, "y": 0.5}, "text": "Biomes", "desc": {"cave_default": "Underground"}, "order": 1, "value": "cave_default"}, "touchstone": {"image": {"x": 0.3125, "y": 0.5}, "text": "Touch Stones", "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "order": 17, "value": "default"}, "world_size": {"image": {"x": 0.75, "y": 0.5}, "text": "World Size", "desc": {"small": "Small", "medium": "Medium", "default": "Large", "huge": "Huge"}, "order": 3, "value": "default"}, "branching": {"image": {"x": 0.5625, "y": 0.5}, "text": "Branches", "desc": {"never": "Never", "least": "Least", "default": "Default", "most": "Most", "random": "Random"}, "order": 4, "value": "default"}, "loop": {"image": {"x": 0.625, "y": 0.5}, "text": "Loops", "desc": {"never": "Never", "default": "Default", "always": "Always"}, "order": 5, "value": "default"}, "start_location": {"image": {"x": 0.8125, "y": 0.5}, "text": "Spawn Area", "desc": {"caves": "Caves"}, "order": 2, "value": "caves"}, "cavelight": {"image": {"x": 0.75, "y": 0.0}, "text": "Sinkhole Lights", "desc": {"never": "None", "veryslow": "Very Slow", "slow": "Slow", "default": "Default", "fast": "Fast", "veryfast": "Very Fast"}, "order": 18, "value": "default"}, "boons": {"image": {"x": 0.75, "y": 0.375}, "text": "Failed Survivors", "desc": {"never": "None", "rare": "Little", "uncommon": "Less", "default": "Default", "often": "More", "mostly": "Lots", "always": "Tons", "insane": "Insane"}, "order": 18, "value": "default"}}}}, "WORLDSETTINGS_GROUP": {"resources": {"order": 4, "text": "Resource Regrowth", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "veryslow": "Very Slow", "slow": "Slow", "default": "Default", "fast": "Fast", "veryfast": "Very Fast"}, "items": {"mushtree_regrowth": {"image": {"x": 0.3125, "y": 0.3125}, "text": "Mushroom Trees", "value": "default"}, "mushtree_moon_regrowth": {"image": {"x": 0.375, "y": 0.3125}, "text": "Lunar Mushtrees", "value": "default"}, "flower_cave_regrowth": {"image": {"x": 0.6875, "y": 0.125}, "text": "Light Flower", "value": "default"}, "lightflier_flower_regrowth": {"image": {"x": 0.125, "y": 0.25}, "text": "Lightbug Flower", "value": "default"}, "regrowth": {"image": {"x": 0.0, "y": 0.4375}, "text": "Regrowth Multiplier", "order": 1, "value": "default"}}}, "giants": {"order": 8, "text": "Giants", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "items": {"toadstool": {"image": {"x": 0.625, "y": 0.5}, "text": "Toadstool", "value": "default"}, "daywalker": {"image": {"x": 0.6875, "y": 0.0625}, "text": "Nightmare Werepig", "value": "default"}, "spiderqueen": {"image": {"x": 0.9375, "y": 0.4375}, "text": "Spider Queen", "value": "default"}, "liefs": {"image": {"x": 0.9375, "y": 0.1875}, "text": "Treeguards", "value": "default"}, "fruitfly": {"image": {"x": 0.875, "y": 0.125}, "text": "Lord of the Fruit Flies", "value": "default"}}}, "lunar_mutations": {"order": 9, "text": "Lunar Mutations", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "default": "Default"}, "items": {"mutated_birds": {"image": {"x": 0.5, "y": 0.3125}, "text": "Mutated Birds", "value": "default"}, "mutated_merm": {"image": {"x": 0.8125, "y": 0.3125}, "text": "Mutated Merms", "value": "default"}, "mutated_spiderqueen": {"image": {"x": 0.875, "y": 0.3125}, "text": "Shattered Spider Holes", "value": "default"}, "moon_spider": {"image": {"x": 0.0625, "y": 0.3125}, "text": "Shattered Spiders", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}}}, "animals": {"order": 6, "text": "Creatures", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "items": {"grassgekkos": {"image": {"x": 0.25, "y": 0.1875}, "text": "Grass Gekko Morphing", "value": "default"}, "dustmoths": {"image": {"x": 0.125, "y": 0.125}, "text": "Dust Moths", "value": "default"}, "pigs_setting": {"image": {"x": 0.5, "y": 0.375}, "text": "Pigs", "value": "default"}, "slurtles_setting": {"image": {"x": 0.625, "y": 0.4375}, "text": "Slurtles", "value": "default"}, "mushgnome": {"image": {"x": 0.25, "y": 0.3125}, "text": "Mush Gnomes", "value": "default"}, "monkey_setting": {"image": {"x": 0.875, "y": 0.25}, "text": "Splumonkeys", "value": "default"}, "lightfliers": {"image": {"x": 0.0625, "y": 0.25}, "text": "Bulbous Lightbugs", "value": "default"}, "rocky_setting": {"image": {"x": 0.125, "y": 0.4375}, "text": "Rock Lobsters", "value": "default"}, "snurtles": {"image": {"x": 0.75, "y": 0.4375}, "text": "Snurtles", "value": "default"}, "bunnymen_setting": {"image": {"x": 0.0, "y": 0.0625}, "text": "Bunnymen", "value": "default"}, "moles_setting": {"image": {"x": 0.75, "y": 0.25}, "text": "Moles", "value": "default"}}}, "misc": {"order": 3, "text": "World", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": null, "items": {"rifts_frequency_cave": {"image": {"x": 0.4375, "y": 0.4375}, "text": "Wild Rift Frequency", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "acidrain_enabled": {"image": {"x": 0.0, "y": 0.0}, "text": "Acid Rain", "desc": {"none": "Disabled", "always": "Enabled"}, "value": "always"}, "rifts_enabled_cave": {"image": {"x": 0.4375, "y": 0.4375}, "text": "Wild Rifts", "desc": {"never": "None", "default": "Auto Detect", "always": "Always"}, "value": "default"}, "atriumgate": {"image": {"x": 0.1875, "y": 0.0}, "text": "Ancient Gateway", "desc": {"veryslow": "Very Slow", "slow": "Slow", "default": "Default", "fast": "Fast", "veryfast": "Very Fast"}, "value": "default"}, "wormattacks_boss": {"image": {"x": 0.3125, "y": 0.5625}, "text": "Great Worm", "desc": {"never": "Never", "rare": "Rare", "default": "Default", "often": "Often", "always": "Always"}, "value": "default"}, "wormattacks": {"image": {"x": 0.25, "y": 0.5625}, "text": "Cave Worm Attacks", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "earthquakes": {"image": {"x": 0.1875, "y": 0.125}, "text": "Earthquakes", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}, "weather": {"image": {"x": 0.875, "y": 0.375}, "text": "Rain", "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "value": "default"}}}, "monsters": {"order": 7, "text": "Hostile Creatures", "atlas": {"name": "worldsettings_customization", "width": 2048, "height": 2048, "item_size": 128}, "desc": {"never": "None", "rare": "Little", "default": "Default", "often": "More", "always": "Tons"}, "items": {"chest_mimics": {"image": {"x": 0.3125, "y": 0.0625}, "text": "Ornery Chests", "value": "default"}, "spiders_setting": {"image": {"x": 0.0, "y": 0.5}, "text": "Spiders", "value": "default"}, "spider_spitter": {"image": {"x": 0.1875, "y": 0.5}, "text": "Spitter Spiders", "value": "default"}, "merms": {"image": {"x": 0.5625, "y": 0.25}, "text": "Merms", "value": "default"}, "bats_setting": {"image": {"x": 0.4375, "y": 0.0}, "text": "Bats", "value": "default"}, "spider_warriors": {"image": {"x": 0.25, "y": 0.5}, "text": "Spider Warriors", "desc": {"never": "None", "default": "Default"}, "value": "default"}, "spider_dropper": {"image": {"x": 0.0625, "y": 0.5}, "text": "Dangling Depth Dwellers", "value": "default"}, "spider_hider": {"image": {"x": 0.125, "y": 0.5}, "text": "Cave Spiders", "value": "default"}, "nightmarecreatures": {"image": {"x": 0.0, "y": 0.375}, "text": "Ruins Nightmares", "value": "default"}, "molebats": {"image": {"x": 0.6875, "y": 0.25}, "text": "Naked Mole Bats", "value": "default"}, "itemmimics": {"image": {"x": 0.6875, "y": 0.1875}, "text": "Mimicreeps", "value": "default"}}}}}}} ================================================ FILE: scripts/py-dst-cli/main.py ================================================ import json from http.server import BaseHTTPRequestHandler, HTTPServer import dst_version import parse_world_setting import parse_world_webp import sys import os import sched import time world_gen_path = sys.argv[1] # 初始化调度器 scheduler = sched.scheduler(time.time, time.sleep) def gen_world_iamge_job(path): print("定时任务--生成世界misc文件正在执行, 参数为:", path) parse_world_webp.download_dst_scripts() def gen_world_setting_job(path): print("定时任务--生成世界json文件正在执行, 参数为:", path) datadata = parse_world_setting.parse_world_setting() import json if not os.path.exists('data'): os.mkdir('data') with open('data/dst_world_setting.json', 'w', encoding='utf-8') as f: f.write(json.dumps(datadata, ensure_ascii=False)) def run(): scheduler.enter(10, 1, gen_world_iamge_job, (world_gen_path,)) scheduler.enter(20, 1, gen_world_setting_job, (world_gen_path,)) scheduler.run() # 循环执行任务 while True: run() ''' class DstWorldHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path.startswith('/py/dst/version/'): self.getDstVersion() elif self.path.startswith('/py/dst/world/setting/webp'): self.getDstWorldSettingWebp() elif self.path.startswith('/py/dst/world/setting/json'): self.getDstWorldSettingJson() else: self.send_error(404) def getDstVersion(self): version = dst_version.get_dst_version() self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps(version).encode()) def getDstWorldSettingWebp(self): parse_world_webp.download_dst_scripts() self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps("ok").encode()) def getDstWorldSettingJson(self): response = parse_world_setting.parse_world_setting() self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps(response).encode()) PORT = 8000 httpd = HTTPServer(('127.0.0.1', PORT), DstWorldHandler) print(f'Serving on port {PORT}') httpd.serve_forever() ''' ================================================ FILE: scripts/py-dst-cli/parse_TooManyItemPlus_items.py ================================================ import os import re import json # 定义修饰词规则 SPICE_TRANSLATIONS = { "_SPICE_GARLIC": "蒜", "_SPICE_CHILI": "辣", "_SPICE_SUGAR": "甜", "_SPICE_SALT": "盐", } def parse_po_file(po_file): """解析 .po 文件,从第 9 行开始,返回仅包含 STRINGS.NAMES 的 msgctxt 与 msgstr 的映射""" translations = {} with open(po_file, "r", encoding="utf-8") as f: lines = f.readlines() # 从第 9 行开始解析 lines = lines[8:] msgctxt, msgid, msgstr = None, None, None for line in lines: line = line.strip() if line.startswith("msgctxt") and "STRINGS.NAMES." in line: msgctxt = re.search(r'"STRINGS\.NAMES\.(.+)"', line).group(1) # 提取物品名 elif line.startswith("msgid"): msgid = re.search(r'"(.*)"', line).group(1) # 捕获空字符串 elif line.startswith("msgstr"): msgstr = re.search(r'"(.*)"', line).group(1) # 捕获空字符串 # 只有在 msgctxt、msgid 和 msgstr 都非空时才保存 if msgctxt and msgid and msgstr: translations[msgctxt] = msgstr # 重置状态 msgctxt, msgid, msgstr = None, None, None return translations def apply_spice_rule(item, base_translation): print(item) """根据规则生成修饰后的翻译""" for suffix, spice_translation in SPICE_TRANSLATIONS.items(): if item.endswith(suffix): base_item = item.replace(suffix, "") if base_item in base_translation: return f"{base_translation[base_item]}-{spice_translation}" return "未翻译" def generate_translations(input_folder, po_file, output_file): """生成带翻译的 JSON 数据""" # 解析 .po 文件 translations = parse_po_file(po_file) # 初始化结果字典 result = {} # 遍历输入文件夹,处理分类数据 for filename in os.listdir(input_folder): if filename.endswith(".lua"): category_name = os.path.splitext(filename)[0] file_path = os.path.join(input_folder, filename) with open(file_path, "r", encoding="utf-8") as f: content = f.read() if "return" in content: content = content.split("return", 1)[1].strip().strip("{}") items = [item.strip().strip('"') for item in content.split(",")] result[category_name] = { item: translations.get(item.upper(), apply_spice_rule(item.upper(), translations)) for item in items } # 保存结果为 JSON 文件 with open(output_file, "w", encoding="utf-8") as f: json.dump(result, f, ensure_ascii=False, indent=4) print(f"翻译结果已保存到 {output_file}") # 设置文件路径 input_folder = "./scripts/TMIP/list" # 替换为文件夹路径 po_file = "./chinese_s.po" # 替换为 .po 文件路径 output_file = "tooManyItemPlus.json" # 输出文件路径 # 运行生成函数 generate_translations(input_folder, po_file, output_file) ================================================ FILE: scripts/py-dst-cli/parse_mod.py ================================================ import lupa from functools import reduce import steam.client import steam.client.cdn import steam.core.cm import steam.webapi from steam.exceptions import SteamError import requests import json from io import BytesIO from urllib.parse import urlencode from urllib.request import Request, urlopen import zipfile import math from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import urlparse, parse_qs anonymous = steam.client.SteamClient() anonymous.anonymous_login() steamcdn = steam.client.cdn.CDNClient(anonymous) encoding = 'utf-8' modinfo_lua = 'modinfo.lua' modinfo_chs_lua = 'modinfo_chs.lua' with open('steamapikey.txt', 'r', encoding='utf-8') as key_value: steamapikey = key_value.read() print('从文件读取 steamapikey 成功') def search_mod_list(text='', page=1, num=25): url = 'http://api.steampowered.com/IPublishedFileService/QueryFiles/v1/' data = { 'page': page, 'key': steamapikey, # steam apikey https://steamcommunity.com/dev/apikey 'appid': 322330, # 游戏id 'language': 6, # 0英文,6简中,7繁中 'return_tags': True, # 返回mod详情中的标签 'numperpage': num, # 每页结果 'search_text': text, # 标题或描述中匹配的文字 'return_vote_data': True, 'return_children': True } url = url + '?' + urlencode(data) for _ in range(2): try: req = Request(url=url) response = urlopen(req, timeout=10) mod_data = response.read().decode('utf-8') # print(mod_data) response.close() break except Exception as e: print('搜索mod失败\n', e ) else: return mod_data = json.loads(mod_data).get('response') total = mod_data.get('total') mod_info_full = mod_data.get('publishedfiledetails') mod_list = [] if mod_info_full: for mod_info_raw in mod_info_full: img = mod_info_raw.get('preview_url', '') vote_data = mod_info_raw.get('vote_data', {}) auth = mod_info_raw.get("creator", 0), mod_info = { 'id': mod_info_raw.get('publishedfileid', ''), 'name': mod_info_raw.get('title', ''), 'author': f'https://steamcommunity.com/profiles/{auth}/?xml=1' if auth else '', 'desc': mod_info_raw.get('file_description'), 'time': int(mod_info_raw.get('time_updated', 0)), 'sub': int(mod_info_raw.get('subscriptions', '0')), 'img': img if 'steamuserimages' in img else '', # 'v': [*[i.get('tag')[8:] for i in mod_info_raw.get('tags', '') if i.get('tag', '').startswith('version:')], ''][0], 'vote': {'star': int(vote_data.get('score') * 5) + 1 if vote_data.get('votes_up') + vote_data.get('votes_down') >= 25 else 0, 'num': vote_data.get('votes_up') + vote_data.get('votes_down')} } if mod_info_raw.get("num_children"): mod_info['child'] = list(map(lambda x: x.get('publishedfileid'), mod_info_raw.get("children"))) mod_list.append(mod_info) return {'page': page, 'size': num,'total': total, 'totalPage': 1 if total/num < 1 else math.ceil(total/num),'data': mod_list} def get_mod_base_info(modId: int): url = 'http://api.steampowered.com/IPublishedFileService/GetDetails/v1/' data = { 'key': steamapikey, # steam apikey https://steamcommunity.com/dev/apikey 'language': 6, # 0英文,6简中,7繁中 'publishedfileids[0]': str(modId), # 要查询的发布文件的ID } url = url + '?' + urlencode(data) payload={} headers = {} response = requests.request("GET", url, headers=headers, data=payload, verify=False) data = json.loads(response.text)['response']['publishedfiledetails'][0] if data['result'] != 1: print("get mod error") return {} img = data.get('preview_url', '') author = data.get('creator') return { 'id': data.get('publishedfileid'), 'name': data.get('title'), 'last_time': data.get('time_updated'), "description": data.get("file_description"), 'auth': f'https://steamcommunity.com/profiles/{author}/?xml=1' if author else '', 'file_url': data.get('file_url'), 'img': f'{img}?imw=64&imh=64&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=true' if 'steamuserimages' in img else '', 'v': [*[i.get('tag')[8:] for i in data.get('tags', '') if i.get('tag', '').startswith('version:')], ''][0], 'creator_appid': data.get('creator_appid'), 'consumer_appid': data.get('consumer_appid'), } def check_is_dst_mod(mod_info): creator_appid, consumer_appid = mod_info.get('creator_appid'), mod_info.get('consumer_appid') if not (creator_appid == 245850 and consumer_appid == 322330): print('%s 不是饥荒联机版 mod', mod_info.get("id")) return False return True def get_mod_info(modId: int): # 获取基础信息 mod_info = get_mod_base_info(modId) if not check_is_dst_mod(mod_info): return {} file_url = mod_info['file_url'] if file_url: mod_type = 'v1' mod_config = get_mod_config_file_by_url(file_url=file_url) else: mod_config = get_mod_config_file_by_steamcmd(modId=modId) mod_type = 'v2' # 获取 mod 文件 mod_info['mod_type'] = mod_type mod_info['mod_config'] = mod_config return mod_info def get_mod_config_file_by_url(file_url: str): status, modinfo = 0, {'modinfo': b'', 'modinfo_chs': b''} resp_input_io = BytesIO() isSuccess = False for i in range(3): try: req = Request(url=file_url) res = urlopen(req, timeout=10) resp_input_io.write(res.read()) res.close() isSuccess = True break except Exception as e: print("下载失败 \n", e, file_url) if not isSuccess: return {} with zipfile.ZipFile(resp_input_io) as file_zip: namelist = file_zip.namelist() if modinfo_lua in namelist: modinfo['modinfo'] = file_zip.read(modinfo_lua) if modinfo_chs_lua in namelist: modinfo['modinfo_chs'] = file_zip.read(modinfo_chs_lua) resp_input_io.close() data = modinfo['modinfo'].decode(encoding) return lua_runtime(data) def get_mod_config_file_by_steamcmd(modId: int): return get_mod_info_dict(modId=modId) #TODO 解决并发问题 ''' lock 使用一个cache{modId: xxx, semaphore: xxx, mod: xxx} init cache 初始化信号量 unlock 执行IO 其他等待 mod 数据返回 ''' def get_mod_info_dict(modId:int): status, modinfo = 0, {'modinfo':b'', 'modinfo_chs': b''} mod_item = steamcdn.get_manifest_for_workshop_item(modId) modinfo_names = ['modinfo.lua', 'modinfo_chs.lua'] modinfo_list = list(filter(lambda x: x.filename in modinfo_names, mod_item.iter_files() )) if not modinfo: print("未找到modinfo", modId) for info in modinfo_list: modinfo[info.filename[:-4]] = info.read() status = 1 data = modinfo['modinfo'].decode(encoding) return lua_runtime(data) def lua_runtime(data: bytes): lua = lupa.LuaRuntime() lang='zh' # lupa 全局变量 lupag = ['locale', 'folder_name', 'ChooseTranslationTable'] + ['print', 'rawlen', 'loadfile', 'rawequal', 'pairs', '_VERSION', 'select', 'pcall', 'debug', 'io', 'getmetatable', 'assert', 'package', 'os', 'warn', 'next', 'load', 'tostring', 'setmetatable', 'rawget', 'coroutine', 'tonumber', 'error', 'collectgarbage', 'python', 'utf8', 'math', 'ipairs', 'rawset', 'type', 'xpcall', '_G', 'table', 'dofile', 'require', 'string'] # 模拟运行环境 lua.execute(f'locale = "{lang}"') lua.execute(f'folder_name = "workshop-{modId}"') lua.execute(f'ChooseTranslationTable = function(tbl) return tbl["{lang}"] or tbl[1] end') # 开始处理数据 lua.execute(data) # 选取需要的值并转为 python 对象 g = lua.globals() # 选择白名单或黑名单模式 info_dict = {key: table_dict(g[key]) for key in filter(lambda x: x not in lupag, g)} # info_dict = {key: table_dict(g[key]) for key in filter(lambda x: x in info_list_full, g)} # 去除空值 info_dict = {i: j for i, j in info_dict.items() if j or j is False or j == 0} return info_dict def table_dict(lua_table): if lupa.lua_type(lua_table) == 'table': keys = list(lua_table) # 假如lupa.table为空,或keys都是整数,且从数字 1 开始以 1 为单位递增,则认为是列表,否则为字典 if reduce(lambda x, y: x and isinstance(y, int), keys, len(keys) == 0 or keys[0] == 1): # 为空或首项为 1,全为整数 if all(map(lambda x, y: x + 1 == y, keys[:-1], keys[1:])): # 以 1 为单位递增 return list(map(lambda x: table_dict(x), lua_table.values())) return dict(map(lambda x, y: (x, table_dict(y)), keys, lua_table.values())) # 由于需要用于解析 modinfo 为 json 格式,所以不支持函数,这里直接删掉 if lupa.lua_type(lua_table) == 'function': return '这里原本是个函数,不过已经被我干掉了' return lua_table modId = 2505341606 # mod_info_dict = get_mod_info_dict(modId) # print(mod_info_dict) #print(get_mod_base_info(modId=modId)) # 1216718131 # print(get_mod_info(modId=modId)) def get_dst_version(): # 0 下载失败, 1 下载成功, 2 内容为空 for _ in range(3): try: # b = next(steamcdn.get_manifests(343050, filter_func=lambda x, y: x == 343052)) # version = next(b.iter_files('version.txt')).read().decode('utf-8').strip() version = [*steamcdn.iter_files(343050, 'version.txt', filter_func=lambda x, y: x == 343052)] if not version: return 0 print(version) version = version[0].read().decode('utf-8').strip() # print(version) return version except SteamError as e: print('获取版本失败', e) return 0 class ModHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path.startswith('/py/mod/'): self.mod_api() elif self.path.startswith('/py/search/mod'): self.search_api() elif self.path.startswith('/py/version'): self.dst_version_api() else: self.send_error(404) def mod_api(self): mod_id = self.path.split('/')[3] mod_info = get_mod_info(int(mod_id)) response = {'modInfo': mod_info} self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps(response).encode()) def search_api(self): query = parse_qs(urlparse(self.path).query) search_text = query['text'][0] page = query['page'][0] size = query['size'][0] print(search_text, page, size) response = search_mod_list(search_text, int(page), int(size)) self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps(response).encode()) def dst_version_api(self): response = get_dst_version() self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps(response).encode()) PORT = 8000 httpd = HTTPServer(('localhost', PORT), ModHandler) print(f'Serving on port {PORT}') httpd.serve_forever() ================================================ FILE: scripts/py-dst-cli/parse_world_setting.py ================================================ ##!/usr/bin/python3 # -*- coding: utf-8 -*- import os from functools import reduce from os.path import join as pjoin from re import compile, findall, search, sub import lupa def table_dict(lua_table): if lupa.lua_type(lua_table) == 'table': keys = list(lua_table) # 假如lupa.table为空,或keys都是整数,且从数字 1 开始以 1 为单位递增,则认为是列表,否则为字典 if reduce(lambda x, y: x and isinstance(y, int), keys, len(keys) == 0 or keys[0] == 1): # 为空或首项为 1,全为整数 if all(map(lambda x, y: x + 1 == y, keys[:-1], keys[1:])): # 以 1 为单位递增 return list(map(lambda x: table_dict(x), lua_table.values())) new_dict = dict(map(lambda x, y: (x, table_dict(y)), keys, lua_table.values())) if 'desc' in new_dict: # task_set 和 start_location 的 desc 是个函数,需要调用一下返回实际值 for i, j in new_dict.items(): if lupa.lua_type(j) == 'function': new_dict[i] = {world: table_dict(j(world)) for world in new_dict.get('world', [])} return new_dict return lua_table def dict_table(py_dict, lua_temp): # dict 转 table。列表之类类型的转过去会有索引,table_from 的问题 if isinstance(py_dict, dict): return lua_temp.table_from( {i: (dict_table(j, lua_temp) if isinstance(j, (dict, list, tuple, set)) else j) for i, j in py_dict.items()}) if isinstance(py_dict, (list, tuple, set)): return lua_temp.table_from([(dict_table(i, lua_temp) if isinstance(i, (dict, list, tuple, set)) else i) for i in py_dict]) return py_dict def scan(dict_scan, num, key_set): # 返回指定深度的 keys 集合, key_set初始传入空set if num != 0: for value in dict_scan.values(): if isinstance(value, dict): key_set = key_set | scan(value, num - 1, key_set) return key_set return key_set | set(dict_scan) def parse_po(path_po): # 把 .po 文件按照 msgctxt: msgstr 的格式转为字典,再以 . 的深度分割 keys。这里为了效率主要转了 UI 部分的 print('开始通过 .po 文件 获取翻译') with open(path_po, 'rb') as f: f.seek(-50000, 2) data = f.read() while b'"STRINGS.T' not in data: f.seek(-100000, 1) data = f.read(50000) + data data = data.decode('utf-8').replace('\r\n', '\n') pattern = compile(r'\nmsgctxt\s*"(.*)"\nmsgid\s*"(.*)"\nmsgstr\s*"(.*)"') dict_zh_split, dict_en_split = {}, {} print('获取中文翻译') dict_zh = {i[0]: i[2] for i in pattern.findall(data)} # 因为 costomize 中有连接字符串的,所以这里不能构建成一个字典,会出错 for i, j in dict_zh.items(): split_key(dict_zh_split, i.split("."), j) # print('获取英文对照') dict_en = {i[0]: i[1] for i in pattern.findall(data)} # 因为 costomize 中有连接字符串的,所以这里不能构建成一个字典,会出错 for i, j in dict_en.items(): split_key(dict_en_split, i.split("."), j) dict_split = {'zh': dict_zh_split} if dict_en_split: dict_split['en'] = dict_en_split return dict_split def split_key(dict_split, list_split, value): # 以列表值为 keys 补全字典深度。用于分割 dict 的 keys,所以叫 split if not list_split: return if list_split[0] not in dict_split: dict_split[list_split[0]] = value if len(list_split) == 1 else {} split_key(dict_split.get(list_split.pop(0)), list_split, value) def creat_newdata(path_cus, new_cus): # 删去local、不必要的require 和不需要的内容 with open(path_cus + '.lua', 'r') as f: data = f.read() if 'local MOD_WORLDSETTINGS_GROUP' in data: data = data[:data.find('local MOD_WORLDSETTINGS_GROUP')] data = sub(r'local [^=]+?\n', '', data).replace('local ', '') data = sub(r'require(?![^\n]+?(?=tasksets"|startlocations"))', '', data) with open(new_cus + '.lua', 'w+') as f: f.write(data) def parse_cus(lua_cus, po): print('准备解析 customize.lua 文件') new_cus = lua_cus + '_tmp' creat_newdata(lua_cus, new_cus) # 删去多余的不需要的数据并另存 print('准备运行环境') lua = lupa.LuaRuntime() lua.execute('function IsNotConsole() return true end') # IsNotConsole() 不是 PS4 或 XBONE 就返回 True # for customize lua.execute('function IsConsole() return false end') # IsConsole() 是 PS4 或 XBONE 就返回 True lua.execute('function IsPS4() return false end') # IsPS4() 不是 PS4 就返回False # for customize lua.execute('ModManager = {}') # for startlocations lua.require('class') # for util lua.require('util') # for startlocations lua.require('constants') # 新年活动相关 lua.require("strict") dict_po = parse_po(po) options_list = ['WORLDGEN_GROUP', 'WORLDSETTINGS_GROUP'] # 所需数据列表 misc_list = ['WORLDGEN_MISC', 'WORLDSETTINGS_MISC'] # 所需数据列表 options = {} print('解析 customize.lua 文件,语言:%s', ', '.join(dict_po.keys())) # 获取英文版的应该可以通过导入strings来做?应该不需要通过 .po 文件匹配 for lang, tran in dict_po.items(): strings = dict_table(tran.get('STRINGS'), lua) if strings: pass lua.execute('STRINGS=python.eval("strings")') # 为了翻译,也免去要先给 STRINGS 加引号之类的麻烦事 # lua.execute('POT_GENERATION = true') # lua.require('strings') lua.require(new_cus) # 终于开始干正事了。导入的 tasksets 会自动打印一些东西出来 options[lang] = {'setting': {i: table_dict(lua.globals()[i]) for i in options_list if i in lua.globals()}, 'translate': tran} for package in list(lua.globals().package.loaded): # 清除加载的 customize 模块,避免下次 require 时不加载 if 'map/' in package: lua.execute(f'package.loaded["{package}"]=nil') # table.remove 不能用,显示 package.loaded 长度为0 miscs = {i: table_dict(lua.globals()[i]) for i in misc_list if i in lua.globals()} print('解析 customize.lua 文件完毕') return options, miscs def parse_option(group_dict, path_base): print('重新组织设置格式') print('这里写的太什么了,不好插日志') result = {} img_info = {} img_name = '' for lang, opt in group_dict.items(): setting, translate = opt.values() result[lang] = {'forest': {}, 'cave': {}} for group, group_value in setting.items(): for world_type in result[lang].values(): world_type[group] = {} for com, com_value in group_value.items(): desc_val = com_value.get('desc') if desc_val: desc_val = {i['data']: i['text'] for i in desc_val} for world, world_value in result.get(lang).items(): img_name = com_value.get('atlas', '').replace('images/', '').replace('.xml', '') if img_name not in img_info: with open(pjoin(path_base, com_value.get('atlas')), 'r', encoding='utf-8') as f: data = f.read() image_filename = search('filename="([^"]+)"', data).group(1) with open(pjoin(path_base, 'images', image_filename), 'rb') as f: img_data = f.read(96) image_width, image_height = int(img_data[88:90].hex(), 16), int(img_data[90:92].hex(), 16) img_width_start, img_width_end = search(r'u1="([^"]+?)"\s*?u2="([^"]+?)"', data).groups() img_item_width = int(image_width / round(1 / (float(img_width_end) - float(img_width_start)))) item_num_w, item_num_h = image_width / img_item_width, image_height / img_item_width img_pos = {i[0]: {'x': round(float(i[1]) * item_num_w) / item_num_w, 'y': 1 - round(float(i[2]) * item_num_h) / item_num_h} for i in findall(r'", i, v.userid, v.name, v.prefab)) end end function GetPlayerData(kuid, uuid) local result = { uuid = uuid, kuid = kuid, success = false, error = nil, data = {} } -- 获取玩家 local player = UserToPlayer(kuid) if not player then result.error = "Player not found with kuid: " .. tostring(kuid) return result end result.success = true -- 基础信息 local data = { name = player.name or player.prefab or "Unknown", prefab = player.prefab, health = { current = player.components.health and player.components.health.currenthealth or 0, max = player.components.health and player.components.health.maxhealth or 0, percent = player.components.health and math.floor(player.components.health:GetPercent() * 100) or 0 }, hunger = { current = player.components.hunger and player.components.hunger.current or 0, max = player.components.hunger and player.components.hunger.max or 0, percent = player.components.hunger and math.floor(player.components.hunger:GetPercent() * 100) or 0 }, sanity = { current = player.components.sanity and player.components.sanity.current or 0, max = player.components.sanity and player.components.sanity.max or 0, percent = player.components.sanity and math.floor(player.components.sanity:GetPercent() * 100) or 0 }, temperature = player.components.temperature and math.floor(player.components.temperature.current) or 0, moisture = player.components.moisture and math.floor(player.components.moisture:GetMoisture()) or 0 } local inv = player.components.inventory -- 手部装备 local handItem = inv:GetEquippedItem(EQUIPSLOTS.HANDS) data.hand_equipment = handItem and { prefab = handItem.prefab, name = handItem.name or handItem.prefab, count = handItem.components.stackable and handItem.components.stackable.stacksize or 1, durability = handItem.components.finiteuses and math.floor(handItem.components.finiteuses:GetPercent() * 100) or nil, fuel = handItem.components.fueled and math.floor(handItem.components.fueled:GetPercent() * 100) or nil } or nil -- 头部装备 local headItem = inv:GetEquippedItem(EQUIPSLOTS.HEAD) data.head_equipment = headItem and { prefab = headItem.prefab, name = headItem.name or headItem.prefab, count = headItem.components.stackable and headItem.components.stackable.stacksize or 1, durability = headItem.components.finiteuses and math.floor(headItem.components.finiteuses:GetPercent() * 100) or nil, armor = headItem.components.armor and math.floor(headItem.components.armor:GetPercent() * 100) or nil } or nil -- 身体装备(通常是背包或盔甲) local bodyItem = inv:GetEquippedItem(EQUIPSLOTS.BODY) local backpack = nil if bodyItem then -- 判断是否为背包(有容器组件) if bodyItem.components.container then backpack = bodyItem data.body_equipment = { type = "backpack", prefab = bodyItem.prefab, name = bodyItem.name or bodyItem.prefab, slots = bodyItem.components.container.numslots } else -- 普通盔甲/衣服 data.body_equipment = { type = "armor", prefab = bodyItem.prefab, name = bodyItem.name or bodyItem.prefab, durability = bodyItem.components.armor and math.floor(bodyItem.components.armor:GetPercent() * 100) or nil } end else data.body_equipment = nil end -- 背包物品 data.backpack_items = {} if backpack and backpack.components.container then local container = backpack.components.container for i = 1, container.numslots do local item = container.slots[i] if item then table.insert(data.backpack_items, { slot = i, prefab = item.prefab, name = item.name or item.prefab, count = item.components.stackable and item.components.stackable.stacksize or 1, freshness = item.components.perishable and math.floor(item.components.perishable:GetPercent() * 100) or nil, durability = item.components.finiteuses and math.floor(item.components.finiteuses:GetPercent() * 100) or nil }) end end end -- 物品栏(15格) data.inventory_items = {} for i = 1, 15 do local item = inv.itemslots[i] if item then table.insert(data.inventory_items, { slot = i, prefab = item.prefab, name = item.name or item.prefab, count = item.components.stackable and item.components.stackable.stacksize or 1, freshness = item.components.perishable and math.floor(item.components.perishable:GetPercent() * 100) or nil, durability = item.components.finiteuses and math.floor(item.components.finiteuses:GetPercent() * 100) or nil, fuel = item.components.fueled and math.floor(item.components.fueled:GetPercent() * 100) or nil }) end end -- 统计信息 data.stats = { inventory_count = #data.inventory_items, backpack_count = #data.backpack_items, total_items = #data.inventory_items + #data.backpack_items } result.data = data return result end -- JSON 编码辅助函数(简单版) function ToJSON(obj, indent) indent = indent or 0 local spaces = string.rep(" ", indent) local result = {} if type(obj) == "table" then local isArray = #obj > 0 table.insert(result, isArray and "[" or "{") local items = {} if isArray then for _, v in ipairs(obj) do table.insert(items, ToJSON(v, indent + 1)) end else for k, v in pairs(obj) do local key = type(k) == "string" and ('"' .. k .. '":') or ('"' .. tostring(k) .. '":') table.insert(items, spaces .. " " .. key .. ToJSON(v, indent + 1)) end end table.insert(result, table.concat(items, ",\n")) table.insert(result, spaces .. (isArray and "]" or "}")) elseif type(obj) == "string" then return '"' .. obj:gsub('"', '\\"') .. '"' elseif type(obj) == "number" or type(obj) == "boolean" then return tostring(obj) elseif obj == nil then return "null" end return table.concat(result, "\n") end -- JSON 编码(压缩成一行) function ToJSONStr(obj) local parts = {} local function serialize(o) if type(o) == "table" then local isArray = #o > 0 table.insert(parts, isArray and "[" or "{") local first = true if isArray then for _, v in ipairs(o) do if not first then table.insert(parts, ",") end first = false serialize(v) end else for k, v in pairs(o) do if not first then table.insert(parts, ",") end first = false table.insert(parts, '"' .. tostring(k) .. '":') serialize(v) end end table.insert(parts, isArray and "]" or "}") elseif type(o) == "string" then -- 转义特殊字符 local s = o:gsub('\\', '\\\\'):gsub('"', '\\"'):gsub('\n', '\\n'):gsub('\r', '\\r'):gsub('\t', '\\t') table.insert(parts, '"' .. s .. '"') elseif type(o) == "number" then table.insert(parts, tostring(o)) elseif type(o) == "boolean" then table.insert(parts, o and "true" or "false") elseif o == nil then table.insert(parts, "null") end end serialize(obj) return table.concat(parts) end ================================================ FILE: static/template/caves_server.ini ================================================ [NETWORK] server_port = {{.ServerPort}} [SHARD] is_master = {{.IsMaster}} name = {{.Name}} id = {{.Id}} [ACCOUNT] encode_user_path = {{.EncodeUserPath}} ================================================ FILE: static/template/cluster.ini ================================================ [GAMEPLAY] #游戏模式,可选 survival,endless,wilderness game_mode = {{.GameMode}} #最大玩家人数 (上限16) max_players = {{.MaxPlayers}} #是否开启玩家对战 pvp = {{.Pvp}} #没人时服务器暂停 pause_when_empty = {{.PauseWhenNobody}} #投票重启世界 vote_enabled = {{.VoteEnabled}} #投票踢人 vote_kick_enabled = false [NETWORK] #局域网游戏 lan_only_cluster = false #游戏偏好 cooperative,competitive,social,madness cluster_intention = {{.ClusterIntention}} #服务器密码 cluster_password = {{.ClusterPassword}} #服务器描述 cluster_description = {{.ClusterDescription}} #服务器名称 cluster_name = {{.ClusterName}} #离线服务器,只有局域网用户能加入,并且依赖所有Steam的任何功能都失效,比如礼物掉落 offline_cluster = false #服务器语言 cluster_language = zh #预留位 whitelist_slots = 0 #每秒通信次数,越高体验越好,但是会增大服务负担 tick_rate = 15 [MISC] #是否开启控制台 console_enabled = true #最大快照数量 max_snapshots = {{.MaxSnapshots}} [SHARD] #服务器共享,开启洞穴必须要开启这个 shard_enabled = true #服务器监听的地址,当所有实例都运行在同一台机器,可填写 127.0.0.1,会被server.ini 覆盖 bind_ip = 127.0.0.1 #master 服务器的 IP,针对非 master 服务器,若与 master 服务器运行在同一台机器时,可填写 127.0.0.1,会被 server.ini 覆盖 master_ip = 127.0.0.1 #监听 master 服务器的 UDP 端口,所有连接至 master 服务器的非 master 服务器必须相同 master_port = 10888 #连接密码,每台服务器必须相同,会被server.ini 覆盖 cluster_key = defaultPass [STEAM] steam_group_only = false # 只允许某 Steam 组的成员加入 steam_group_id = 0 # 指定某个 Steam 组,填写组 ID steam_group_admins = false # 开启后,Steam 组的管理员拥有服务器的管理权限 ================================================ FILE: static/template/cluster2.ini ================================================ [GAMEPLAY] #游戏模式,可选 survival,endless,wilderness game_mode = {{.GameMode}} #最大玩家人数 (上限16) max_players = {{.MaxPlayers}} #是否开启玩家对战 pvp = {{.Pvp}} #没人时服务器暂停 pause_when_empty = {{.PauseWhenNobody}} #投票重启世界 vote_enabled = {{.VoteEnabled}} #投票踢人 vote_kick_enabled = {{.VoteKickEnabled}} [NETWORK] #局域网游戏 lan_only_cluster = {{.LanOnlyCluster}} #游戏偏好 cooperative,competitive,social,madness cluster_intention = {{.ClusterIntention}} #服务器密码 cluster_password = {{.ClusterPassword}} #服务器描述 cluster_description = {{.ClusterDescription}} #服务器名称 cluster_name = {{.ClusterName}} #离线服务器,只有局域网用户能加入,并且依赖所有Steam的任何功能都失效,比如礼物掉落 offline_cluster = {{.OfflineCluster}} #服务器语言 cluster_language = {{.ClusterLanguage}} #预留位 whitelist_slots = {{.WhitelistSlots}} #每秒通信次数,越高体验越好,但是会增大服务负担 tick_rate = {{.TickRate}} [MISC] #是否开启控制台 console_enabled = {{.ConsoleEnabled}} #最大快照数量 max_snapshots = {{.MaxSnapshots}} [SHARD] #服务器共享,开启洞穴必须要开启这个 shard_enabled = {{.ShardEnabled}} #服务器监听的地址,当所有实例都运行在同一台机器,可填写 127.0.0.1,会被server.ini 覆盖 bind_ip = {{.BindIp}} #master 服务器的 IP,针对非 master 服务器,若与 master 服务器运行在同一台机器时,可填写 127.0.0.1,会被 server.ini 覆盖 master_ip = {{.MasterIp}} #监听 master 服务器的 UDP 端口,所有连接至 master 服务器的非 master 服务器必须相同 master_port = {{.MasterPort}} #连接密码,每台服务器必须相同,会被server.ini 覆盖 cluster_key = {{.ClusterKey}} [STEAM] # 只允许某 Steam 组的成员加入 steam_group_only = {{.SteamGroupOnly}} # 指定某个 Steam 组,填写组 ID steam_group_id = {{.SteamGroupId}} # 开启后,Steam 组的管理员拥有服务器的管理权限 steam_group_admins = {{.SteamGroupAdmins}} ================================================ FILE: static/template/master_server.ini ================================================ [NETWORK] server_port = {{.ServerPort}} [SHARD] is_master = {{.IsMaster}} name = {{.Name}} id = {{.Id}} [ACCOUNT] encode_user_path = {{.EncodeUserPath}} ================================================ FILE: static/template/server.ini ================================================ [NETWORK] server_port = {{.ServerPort}} [SHARD] is_master = {{.IsMaster}} name = {{.Name}} id = {{.Id}} [ACCOUNT] encode_user_path = {{.EncodeUserPath}} [STEAM] master_server_port = {{.MasterServerPort}} authentication_port = {{.AuthenticationPort}} ================================================ FILE: static/template/test.go ================================================ package main import ( "bytes" "dst-admin-go/vo" "fmt" "text/template" "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/host" "github.com/shirou/gopsutil/mem" ) func main() { GetHostInfo() GetCpuInfo() GetMemInfo() GetDiskInfo() tmpl, err := template.ParseFiles("cluster.ini") CheckErr(err) buf := new(bytes.Buffer) gameConfigVo := vo.GameConfigVO{ ClusterIntention: "这是一个测试", ClusterName: "饥荒萌萌哒", ClusterDescription: "一起来玩啊", GameMode: "endless", Pvp: false, MaxPlayers: 6, Token: "dadmam,dman,dmna m,dnamd", PauseWhenNobody: false, } tmpl.Execute(buf, gameConfigVo) fmt.Printf("buf.String():\n%v\n", buf.String()) } func CheckErr(err error) { if err != nil { panic(err) } } func GetHostInfo() { info, _ := host.Info() fmt.Println(info) } func GetCpuInfo() { } func GetMemInfo() { v, _ := mem.VirtualMemory() // almost every return value is a struct fmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent) // convert to JSON. String() is also implemented //fmt.Println(v) } func GetDiskInfo() { //info, _ := disk.IOCounters() //所有硬盘的io信息 diskPart, err := disk.Partitions(false) if err != nil { fmt.Println(err) } // fmt.Println(diskPart) for _, dp := range diskPart { fmt.Println(dp) diskUsed, _ := disk.Usage(dp.Mountpoint) fmt.Printf("分区总大小: %d MB \n", diskUsed.Total/1024/1024) fmt.Printf("分区使用率: %.3f %% \n", diskUsed.UsedPercent) fmt.Printf("分区inode使用率: %.3f %% \n", diskUsed.InodesUsedPercent) } }