From 7be7d0c5b53e3194a9ba33e8cc53152d41d28375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=B6khan=20=C3=96zelo=C4=9Flu?= Date: Tue, 21 Sep 2021 00:01:43 +0300 Subject: [PATCH] --proxy cmd proxy url handled * proxy related tasks moved to flag.go --> proxyCmd() * default port number added to proxy url * url variable renamed to URL because of name conflict with url pkg --- cmd/flag.go | 24 ++++++++++++++++++++++++ cmd/root.go | 19 ++++++++++++++----- 2 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 cmd/flag.go diff --git a/cmd/flag.go b/cmd/flag.go new file mode 100644 index 0000000..6485595 --- /dev/null +++ b/cmd/flag.go @@ -0,0 +1,24 @@ +package cmd + +import ( + "fmt" + "net/url" +) + +const defaultPort = "1080" + +// proxyCmd parses proxy url and adds default port number if not exists. +func proxyCmd(proxy string) (string, error) { + u, err := url.Parse(proxy) + if err != nil { + err = fmt.Errorf("not valid proxy address: %s", err.Error()) + return "", err + } + if u.Port() == "" { + if proxy[len(proxy)-1] != ':' { + proxy += ":" + } + proxy += defaultPort + } + return proxy, nil +} diff --git a/cmd/root.go b/cmd/root.go index dd32f3b..67ff910 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -8,7 +8,7 @@ import ( ) var ( - url = "" + URL = "" proxy = "" c = src.NewClient() ) @@ -18,9 +18,13 @@ var rootCmd = &cobra.Command{ Short: "gURL is open source CLI tool written in Go.", Args: cobra.MaximumNArgs(1), Run: func(cmd *cobra.Command, args []string) { - url = args[0] - fmt.Println("URL: ", url) - checkFlags() + URL = args[0] + fmt.Println("URL: ", URL) + err := checkFlags() + if err != nil { + fmt.Println(err) + os.Exit(1) + } }, } @@ -34,8 +38,13 @@ func Execute() { } // checkFlags checks the flags, get input, and sets the inputs to Client. -func checkFlags() { +func checkFlags() error { if proxy != "" { + proxy, err := proxyCmd(proxy) + if err != nil { + return err + } c.SetProxy(proxy) } + return nil }