httpFileServer starts an HTTP file server at a specified path.
(path string, logger Logger, listenAndServe func(*http.Server) error, timeout time.Duration)
| 16 | |
| 17 | // httpFileServer starts an HTTP file server at a specified path. |
| 18 | func httpFileServer(path string, logger Logger, listenAndServe func(*http.Server) error, timeout time.Duration) (*http.Server, error) { |
| 19 | // Validate that the directory exists |
| 20 | if _, err := os.Stat(path); os.IsNotExist(err) { |
| 21 | logger.Errorf("Path does not exist: %s", path) |
| 22 | return nil, fmt.Errorf("path does not exist: %s", path) |
| 23 | } |
| 24 | |
| 25 | // Configure the HTTP server |
| 26 | server := &http.Server{ |
| 27 | Addr: "0.0.0.0:" + httpPort, |
| 28 | Handler: http.FileServer(http.Dir(path)), |
| 29 | } |
| 30 | |
| 31 | errChan := make(chan error, 1) |
| 32 | |
| 33 | go func() { |
| 34 | logger.Infof("Starting HTTP file server on %s serving path: %s", server.Addr, path) |
| 35 | errChan <- listenAndServe(server) |
| 36 | }() |
| 37 | |
| 38 | start := time.Now() |
| 39 | for { |
| 40 | select { |
| 41 | case err := <-errChan: |
| 42 | if err != nil { |
| 43 | logger.Errorf("Error starting HTTP server: %v", err) |
| 44 | return nil, err |
| 45 | } |
| 46 | default: |
| 47 | resp, err := http.Get("http://localhost:" + httpPort) |
| 48 | if err == nil && resp.StatusCode == http.StatusOK { |
| 49 | logger.Infof("HTTP server is ready on %s", server.Addr) |
| 50 | return server, nil |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | if time.Since(start) > timeout { |
| 55 | logger.Errorf("Timeout waiting for server to start on port %s", httpPort) |
| 56 | return nil, fmt.Errorf("timeout waiting for server to start on port %s", httpPort) |
| 57 | } |
| 58 | |
| 59 | time.Sleep(500 * time.Millisecond) |
| 60 | } |
| 61 | } |