package cmd import ( "fmt" "log" "net/http" "os" "path/filepath" "github.com/spf13/cobra" ) // serverCmd represents the server command var serverCmd = &cobra.Command{ Use: "server [directory]", Short: "Start a simple HTTP server to serve files from the specified directory", Long: `Start a simple HTTP server to serve files from the specified directory. If no directory is provided, the current directory is used by default. You can specify the port number using the --port (-p) flag. If not provided, the default port is 8080.`, Args: cobra.MaximumNArgs(1), Run: func(cmd *cobra.Command, args []string) { var directory string if len(args) == 1 { directory = args[0] } else { directory, _ = os.Getwd() } directory, err := filepath.Abs(directory) if err != nil { log.Fatalf("Error getting absolute path: %v", err) } port, err := cmd.Flags().GetInt("port") if err != nil { log.Fatalf("Error getting port number: %v", err) } addr := fmt.Sprintf(":%d", port) fmt.Printf("Starting HTTP server for directory: %s\n", directory) http.Handle("/", http.FileServer(http.Dir(directory))) fmt.Printf("Server listening on %s\n", addr) if err := http.ListenAndServe(addr, nil); err != nil { log.Fatalf("Error starting HTTP server: %v", err) } }, } func init() { rootCmd.AddCommand(serverCmd) serverCmd.Flags().IntP("port", "p", 8080, "Port number for the HTTP server") }