package backend import ( "fmt" "net" "net/http" "os" "path/filepath" "strings" "sync" "time" ) type SwaggerFile struct { Name string `json:"name"` Path string `json:"path"` Size int64 `json:"size"` ModifiedTime string `json:"modifiedTime"` } type SwaggerServer struct { server *http.Server port int running bool mu sync.Mutex } var swaggerServer *SwaggerServer var swaggerServerMu sync.Mutex func (a *App) GetSwaggerFiles(dirPath string) ([]SwaggerFile, error) { if dirPath == "" { return nil, fmt.Errorf("directory path is empty") } var files []SwaggerFile err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } if strings.HasSuffix(strings.ToLower(info.Name()), ".swagger.json") { files = append(files, SwaggerFile{ Name: info.Name(), Path: path, Size: info.Size(), ModifiedTime: info.ModTime().Format("2006-01-02 15:04:05"), }) } return nil }) if err != nil { return nil, fmt.Errorf("failed to walk directory: %w", err) } return files, nil } func (a *App) GetSwaggerFileInfo(filePath string) (SwaggerFile, error) { if filePath == "" { return SwaggerFile{}, fmt.Errorf("file path is empty") } info, err := os.Stat(filePath) if err != nil { return SwaggerFile{}, fmt.Errorf("failed to get file info: %w", err) } return SwaggerFile{ Name: info.Name(), Path: filePath, Size: info.Size(), ModifiedTime: info.ModTime().Format("2006-01-02 15:04:05"), }, nil } func (a *App) ReadSwaggerFile(filePath string) (string, error) { if filePath == "" { return "", fmt.Errorf("file path is empty") } content, err := os.ReadFile(filePath) if err != nil { return "", fmt.Errorf("failed to read file: %w", err) } return string(content), nil } func (a *App) StartSwaggerServer(filePath string) (string, error) { if filePath == "" { return "", fmt.Errorf("file path is empty") } swaggerServerMu.Lock() defer swaggerServerMu.Unlock() if swaggerServer != nil && swaggerServer.running { return fmt.Sprintf("http://localhost:%d", swaggerServer.port), nil } port := 8080 for i := 0; i < 100; i++ { listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err == nil { listener.Close() break } port++ } mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { swaggerHTML := `