diff --git a/sling.go b/sling.go index 10e252f..1171f85 100644 --- a/sling.go +++ b/sling.go @@ -208,7 +208,15 @@ func (s *Sling) Path(path string) *Sling { pathURL, pathErr := url.Parse(path) if baseErr == nil && pathErr == nil { s.rawURL = baseURL.ResolveReference(pathURL).String() - return s + } + return s +} + +// Extend simply extends the rawURL by appending path to it using [url.JoinPath]. +// If parsing error occurs, the rawURL is left unmodified. +func (s *Sling) Extend(path string) *Sling { + if u, err := url.JoinPath(s.rawURL, path); err == nil { + s.rawURL = u } return s } diff --git a/sling_test.go b/sling_test.go index c93b6d5..c9930cf 100644 --- a/sling_test.go +++ b/sling_test.go @@ -186,6 +186,27 @@ func TestPathSetter(t *testing.T) { } } +func TestExtend(t *testing.T) { + cases := []struct { + rawURL string + extensions []string + expectedRawURL string + }{ + {"http://a.io", []string{"foo", "bar"}, "http://a.io/foo/bar"}, + {"http://a.io/", []string{"foo", "bar"}, "http://a.io/foo/bar"}, + {"http://a.io/", []string{"/foo", "./bar"}, "http://a.io/foo/bar"}, + } + for _, c := range cases { + sl := New().Base(c.rawURL) + for _, e := range c.extensions { + sl.Extend(e) + } + if sl.rawURL != c.expectedRawURL { + t.Errorf("expected %s, got %s", c.expectedRawURL, sl.rawURL) + } + } +} + func TestMethodSetters(t *testing.T) { cases := []struct { sling *Sling @@ -953,23 +974,23 @@ func TestReceive_errorCreatingRequest(t *testing.T) { } func TestReceive_context(t *testing.T) { - client, mux, server := testServer() - defer server.Close() - mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { - }) - - ctx, fn := context.WithCancel(context.Background()) - defer fn() - - endpoint := New().Client(client).Get("http://example.com/foo") - resp, err := endpoint.New().ReceiveWithContext(ctx, nil, nil) - if err != nil { - t.Errorf("expected nil, got %v", err) - } - - if resp.Request.Context() != ctx { - t.Error("request.Context() is not same as context passed during receive operation") - } + client, mux, server := testServer() + defer server.Close() + mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { + }) + + ctx, fn := context.WithCancel(context.Background()) + defer fn() + + endpoint := New().Client(client).Get("http://example.com/foo") + resp, err := endpoint.New().ReceiveWithContext(ctx, nil, nil) + if err != nil { + t.Errorf("expected nil, got %v", err) + } + + if resp.Request.Context() != ctx { + t.Error("request.Context() is not same as context passed during receive operation") + } } func TestReuseTcpConnections(t *testing.T) {