From 56067e38300ea96e069b416ca171ff96f463d2c3 Mon Sep 17 00:00:00 2001 From: risk danger olson Date: Thu, 22 Dec 2016 14:35:57 -0700 Subject: [PATCH] lfsapi: teach Client how to build a request with an endpoint. --- lfsapi/client.go | 24 ++++++++++++++++++++++++ lfsapi/client_test.go | 22 ++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lfsapi/client.go b/lfsapi/client.go index 5724b74d..7abad05f 100644 --- a/lfsapi/client.go +++ b/lfsapi/client.go @@ -15,6 +15,30 @@ import ( var UserAgent = "git-lfs" +func (c *Client) NewRequest(method string, e Endpoint, suffix string, body interface{}) (*http.Request, error) { + req, err := http.NewRequest(method, joinURL(e.Url, suffix), nil) + if err != nil { + return req, err + } + + if body != nil { + if merr := MarshalToRequest(req, body); merr != nil { + return req, merr + } + } + + return req, err +} + +const slash = "/" + +func joinURL(prefix, suffix string) string { + if strings.HasSuffix(prefix, slash) { + return prefix + suffix + } + return prefix + slash + suffix +} + func (c *Client) Do(req *http.Request) (*http.Response, error) { req.Header.Set("User-Agent", UserAgent) diff --git a/lfsapi/client_test.go b/lfsapi/client_test.go index 9679647b..9a68d014 100644 --- a/lfsapi/client_test.go +++ b/lfsapi/client_test.go @@ -2,6 +2,7 @@ package lfsapi import ( "encoding/json" + "fmt" "net/http" "net/http/httptest" "sync/atomic" @@ -159,3 +160,24 @@ func TestNewClientWithOSSSLVerify(t *testing.T) { assert.True(t, c.SkipSSLVerify) } } + +func TestNewRequest(t *testing.T) { + tests := [][]string{ + {"https://example.com", "a", "https://example.com/a"}, + {"https://example.com/", "a", "https://example.com/a"}, + {"https://example.com/a", "b", "https://example.com/a/b"}, + {"https://example.com/a/", "b", "https://example.com/a/b"}, + } + + for _, test := range tests { + c, err := NewClient(nil, testEnv(map[string]string{ + "lfs.url": test[0], + })) + require.Nil(t, err) + + req, err := c.NewRequest("POST", c.Endpoints.Endpoint("", ""), test[1], nil) + require.Nil(t, err) + assert.Equal(t, "POST", req.Method) + assert.Equal(t, test[2], req.URL.String(), fmt.Sprintf("endpoint: %s, suffix: %s, expected: %s", test[0], test[1], test[2])) + } +}