From 9c9455330ae7f93f581d3673aedbdcc017ef782b Mon Sep 17 00:00:00 2001 From: Nate Walck Date: Thu, 26 Oct 2017 13:01:53 -0400 Subject: [PATCH] Remove u.Scheme as we are handling that just before parsing (#266) Added tests --- cmd/mdmctl/config.go | 33 +++++++++++++++++++------------ cmd/mdmctl/config_test.go | 41 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 12 deletions(-) create mode 100644 cmd/mdmctl/config_test.go diff --git a/cmd/mdmctl/config.go b/cmd/mdmctl/config.go index 444ee83e..822e1397 100644 --- a/cmd/mdmctl/config.go +++ b/cmd/mdmctl/config.go @@ -96,25 +96,34 @@ func setCmd(cfg *ClientConfig, args []string) error { cfg.APIToken = *flToken } - if *flServerURL != "" { - if !(strings.HasPrefix(*flServerURL, "http") || - strings.HasPrefix(*flServerURL, "https")) { - *flServerURL = "https://" + *flServerURL - } - u, err := url.Parse(*flServerURL) - if err != nil { - return err - } - u.Scheme = "https" - u.Path = "/" - cfg.ServerURL = u.String() + validatedURL, err := validateServerURL(*flServerURL) + if err != nil { + return err } + cfg.ServerURL = validatedURL cfg.SkipVerify = *flSkipVerify return SaveClientConfig(cfg) } +func validateServerURL(serverURL string) (string, error) { + if serverURL != "" { + if !(strings.HasPrefix(serverURL, "http") || + strings.HasPrefix(serverURL, "https")) { + serverURL = "https://" + serverURL + } + u, err := url.Parse(serverURL) + if err != nil { + return "", err + } + u.Path = "/" + serverURL = u.String() + } + return serverURL, nil + +} + func clientConfigPath() (string, error) { usr, err := user.Current() if err != nil { diff --git a/cmd/mdmctl/config_test.go b/cmd/mdmctl/config_test.go new file mode 100644 index 00000000..720438e9 --- /dev/null +++ b/cmd/mdmctl/config_test.go @@ -0,0 +1,41 @@ +package main + +import "testing" + +func TestValidateServerURL(t *testing.T) { + + tests := []struct { + name string + input string + expected string + }{ + { + name: "http", + input: "http://localhost:8000", + expected: "http://localhost:8000/", + }, + { + name: "https", + input: "https://localhost:8000", + expected: "https://localhost:8000/", + }, + { + name: "trailing_slash", + input: "https://localhost:8000/", + expected: "https://localhost:8000/", + }, + { + name: "no_prefix", + input: "localhost:8000", + expected: "https://localhost:8000/", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actualURL, _ := validateServerURL(tt.input) + if have, want := actualURL, tt.expected; have != want { + t.Errorf("have %s, want %s", have, want) + } + }) + } +}