From 7c7483b5a5efaa91fe4752d4ebf0326e940a58b7 Mon Sep 17 00:00:00 2001 From: Cyril Tovena Date: Mon, 27 Apr 2020 20:26:09 -0400 Subject: [PATCH] Improve URL building in the logcli to strip trailing /. Fixes #1985. Signed-off-by: Cyril Tovena --- pkg/logcli/client/client.go | 22 ++++++++++++++++++++-- pkg/logcli/client/client_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 pkg/logcli/client/client_test.go diff --git a/pkg/logcli/client/client.go b/pkg/logcli/client/client.go index cf350563bb32..def828bc8d24 100644 --- a/pkg/logcli/client/client.go +++ b/pkg/logcli/client/client.go @@ -7,6 +7,7 @@ import ( "log" "net/http" "net/url" + "path" "strings" "time" @@ -119,7 +120,11 @@ func (c *Client) doQuery(path string, quiet bool) (*loghttp.QueryResponse, error } func (c *Client) doRequest(path string, quiet bool, out interface{}) error { - us := c.Address + path + + us, err := buildURL(c.Address, path) + if err != nil { + return err + } if !quiet { log.Print(us) } @@ -175,7 +180,10 @@ func (c *Client) LiveTailQueryConn(queryStr string, delayFor int, limit int, fro } func (c *Client) wsConnect(path string, quiet bool) (*websocket.Conn, error) { - us := c.Address + path + us, err := buildURL(c.Address, path) + if err != nil { + return nil, err + } tlsConfig, err := config.NewTLSConfig(&c.TLSConfig) if err != nil { @@ -213,3 +221,13 @@ func (c *Client) wsConnect(path string, quiet bool) (*websocket.Conn, error) { return conn, nil } + +// buildURL concats a url `http://foo/bar` with a path `/buzz`. +func buildURL(u, p string) (string, error) { + url, err := url.Parse(u) + if err != nil { + return "", err + } + url.Path = path.Join(url.Path, p) + return url.String(), nil +} diff --git a/pkg/logcli/client/client_test.go b/pkg/logcli/client/client_test.go new file mode 100644 index 000000000000..49d97fa6c1a4 --- /dev/null +++ b/pkg/logcli/client/client_test.go @@ -0,0 +1,28 @@ +package client + +import "testing" + +func Test_buildURL(t *testing.T) { + tests := []struct { + name string + u, p string + want string + wantErr bool + }{ + {"err", "8://2", "/bar", "", true}, + {"strip /", "http://localhost//", "//bar", "http://localhost/bar", false}, + {"sub path", "https://localhost/loki/", "/bar/foo", "https://localhost/loki/bar/foo", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := buildURL(tt.u, tt.p) + if (err != nil) != tt.wantErr { + t.Errorf("buildURL() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("buildURL() = %v, want %v", got, tt.want) + } + }) + } +}