diff --git a/cmd/parse.go b/cmd/parse.go index fcc0092..563aabe 100644 --- a/cmd/parse.go +++ b/cmd/parse.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" "html/template" "net/url" + "strings" ) var parseCmd = &cobra.Command{ @@ -92,13 +93,28 @@ var parseQueryCmd = &cobra.Command{ Short: "parses the given query string and returns them as json or formatted template", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - _, err := url.ParseQuery(args[0]) + // remove leading question mark + in := strings.TrimLeft(args[0], "?") + + parsed, err := url.ParseQuery(in) + + if err != nil { + return err + } + + done, err := doFormat(cmd, parsed) if err != nil { return err } - // @todo output(cmd, out) + if done { + return nil + } + + if err := doJson(cmd, parsed); err != nil { + return err + } return nil }, diff --git a/cmd/parse_test.go b/cmd/parse_test.go index ee008b9..55ff1df 100644 --- a/cmd/parse_test.go +++ b/cmd/parse_test.go @@ -3,6 +3,7 @@ package cmd import ( "encoding/json" "github.com/adrianrudnik/uritool/cmd/cmdtest" + "net/url" "strings" "testing" ) @@ -254,7 +255,7 @@ func TestParseValidUriWithFormat(t *testing.T) { } } -func TestParseStringWithFormat(t *testing.T) { +func TestParseValidUriStringWithFormat(t *testing.T) { setup() in := "http://www.example.com/" @@ -265,3 +266,55 @@ func TestParseStringWithFormat(t *testing.T) { t.Errorf("Expected format is wrong: %s != %s", out, expected) } } + +func TestParseValidQuery(t *testing.T) { + setup() + + in := "this=is&this=isnot" + out, _ := cmdtest.ExecuteCommand(rootCmd, "-n", "parse", "query", in) + + var result url.Values + err := json.Unmarshal([]byte(out), &result) + + if err != nil { + t.Errorf("Could not validate JSON: %s", err) + } + + if len(result.Get("this")) != 2 { + t.Errorf("Expected query parameter count is wrong: %d != %d", len(result.Get("this")), 1) + } + + if result["this"][0] != "is" { + t.Errorf("Expected query parameter array element 0 is wrong: %s != %s", result["this"][0], "is") + } + + if result["this"][1] != "isnot" { + t.Errorf("Expected query parameter array element 0 is wrong: %s != %s", result["this"][1], "isnot") + } +} + +func TestParseValidQueryWithLeadingQuestionMark(t *testing.T) { + setup() + + in := "?this=is&this=isnot" + out, _ := cmdtest.ExecuteCommand(rootCmd, "-n", "parse", "query", in) + + var result url.Values + err := json.Unmarshal([]byte(out), &result) + + if err != nil { + t.Errorf("Could not validate JSON: %s", err) + } + + if len(result.Get("this")) != 2 { + t.Errorf("Expected query parameter count is wrong: %d != %d", len(result.Get("this")), 1) + } + + if result["this"][0] != "is" { + t.Errorf("Expected query parameter array element 0 is wrong: %s != %s", result["this"][0], "is") + } + + if result["this"][1] != "isnot" { + t.Errorf("Expected query parameter array element 0 is wrong: %s != %s", result["this"][1], "isnot") + } +}