|
1 | 1 | package cli |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "context" |
4 | 5 | "fmt" |
5 | | - "net/http" |
6 | | - "net/http/httputil" |
7 | | - "net/url" |
| 6 | + "os" |
| 7 | + "os/signal" |
| 8 | + "syscall" |
8 | 9 |
|
9 | | - "github.com/kernelshard/expose/internal/config" |
10 | 10 | "github.com/spf13/cobra" |
| 11 | + |
| 12 | + "github.com/kernelshard/expose/internal/config" |
| 13 | + "github.com/kernelshard/expose/internal/tunnel" |
11 | 14 | ) |
12 | 15 |
|
13 | 16 | // tunnelCmd represents the 'tunnel' command in the CLI application. |
@@ -40,14 +43,39 @@ func newTunnelCmd() *cobra.Command { |
40 | 43 | // runTunnel sets up a reverse proxy to expose the local server |
41 | 44 | // on the specified port. |
42 | 45 | func runTunnel(port int) error { |
43 | | - fmt.Printf("Exposing localhost:%d\n", port) |
44 | | - fmt.Printf("Local URL: http://localhost:8080\n") |
45 | | - fmt.Println("\nPress Ctrl+C to stop") |
46 | 46 |
|
47 | | - // Create reverse proxy to forward requests |
48 | | - target, _ := url.Parse(fmt.Sprintf("http://localhost:%d", port)) |
49 | | - proxy := httputil.NewSingleHostReverseProxy(target) |
| 47 | + // Create manager |
| 48 | + mgr := tunnel.NewManager(port) |
| 49 | + |
| 50 | + // context with signal handling |
| 51 | + ctx, cancel := context.WithCancel(context.Background()) |
| 52 | + defer cancel() |
| 53 | + |
| 54 | + // handle Ctrl+C, kill pid etc |
| 55 | + sigChan := make(chan os.Signal, 1) |
| 56 | + signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) |
| 57 | + |
| 58 | + // waiting to read from channel is blocking ops, so wait in bg. |
| 59 | + go func() { |
| 60 | + <-sigChan |
| 61 | + fmt.Println("\n\nShutting down...") |
| 62 | + cancel() |
| 63 | + }() |
| 64 | + |
| 65 | + // start in background |
| 66 | + errChan := make(chan error, 1) |
| 67 | + go func() { |
| 68 | + errChan <- mgr.Start(ctx) |
| 69 | + }() |
| 70 | + |
| 71 | + // wait for ready |
| 72 | + <-mgr.Ready() |
| 73 | + |
| 74 | + // Show info |
| 75 | + fmt.Printf("🚀 Starting tunnel for localhost:%d\n\n", port) |
| 76 | + fmt.Printf("✓ Public URL: %s\n", mgr.PublicURL()) |
| 77 | + fmt.Printf("✓ Forwarding to: http://localhost:%d\n\n", port) |
| 78 | + fmt.Println("Press Ctrl+C to stop") |
50 | 79 |
|
51 | | - // Start local server |
52 | | - return http.ListenAndServe(":8080", proxy) |
| 80 | + return <-errChan |
53 | 81 | } |
0 commit comments