summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
Diffstat (limited to 'main.go')
-rw-r--r--main.go74
1 files changed, 74 insertions, 0 deletions
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..75555e6
--- /dev/null
+++ b/main.go
@@ -0,0 +1,74 @@
1package main
2
3import (
4 "errors"
5 "fmt"
6 "log"
7 "net/http"
8 "os"
9 "strings"
10
11 "github.com/spf13/cobra"
12)
13
14var rootCmd = &cobra.Command{
15 Use: "websocket-proxy",
16 Version: "0.1.0",
17 Short: "Proxy TCP connections over a websocket",
18}
19
20var clientCmd = &cobra.Command{
21 Use: "client [server host]",
22 Short: "Act as a client for a websocket-proxy server",
23 Args: func(cmd *cobra.Command, args []string) error {
24 if len(args) != 1 || args[0] == "" {
25 return errors.New("Server host is a required argument")
26 }
27 if !strings.HasPrefix(args[0], "ws://") && !strings.HasPrefix(args[0], "wss://") {
28 return errors.New("Server host format is ws[s]://host[:port]/[path]")
29 }
30 return nil
31 },
32 Run: func(cmd *cobra.Command, args []string) {
33 listenOn := cmd.Flag("listen").Value.String()
34
35 h := &ClientHandler{
36 SocketListenOn: listenOn,
37 WebsocketServer: args[0],
38 }
39
40 log.Printf("Serving on %s", listenOn)
41 h.Run()
42 },
43}
44
45var serverCmd = &cobra.Command{
46 Use: "server [next-hop host]",
47 Short: "Serve websocket proxy client",
48 Args: func(cmd *cobra.Command, args []string) error {
49 if len(args) != 1 || args[0] == "" {
50 return errors.New("Next-hop host is a required argument")
51 }
52 return nil
53 },
54 Run: func(cmd *cobra.Command, args []string) {
55 listenOn := cmd.Flag("listen").Value.String()
56 log.Printf("Serving on %s", listenOn)
57
58 http.Handle("/", NewServerHandler(args[0]))
59 log.Fatal(http.ListenAndServe(listenOn, nil))
60 },
61}
62
63func main() {
64 rootCmd.AddCommand(clientCmd)
65 rootCmd.AddCommand(serverCmd)
66
67 clientCmd.Flags().StringP("listen", "l", ":9013", "[address]:port to bind for serving clients")
68 serverCmd.Flags().StringP("listen", "l", ":9012", "[address]:port to bind for serving clients")
69
70 if err := rootCmd.Execute(); err != nil {
71 fmt.Println(err)
72 os.Exit(1)
73 }
74}