From dad2a7214f666adef9a47e7b39c7be9d894f6c29 Mon Sep 17 00:00:00 2001 From: gm42 Date: Mon, 10 Oct 2016 09:46:21 +0200 Subject: [PATCH 1/2] NewRawRequest method to use a native io.Reader instead of marshalling --- jira.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/jira.go b/jira.go index 70b7e6e..dd203bc 100644 --- a/jira.go +++ b/jira.go @@ -61,6 +61,35 @@ func NewClient(httpClient *http.Client, baseURL string) (*Client, error) { return c, nil } +// NewRawRequest creates an API request. +// A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. +// Relative URLs should always be specified without a preceding slash. +// Allows using an optional native io.Reader for sourcing the request body. +func (c *Client) NewRawRequest(method, urlStr string, body io.Reader) (*http.Request, error) { + rel, err := url.Parse(urlStr) + if err != nil { + return nil, err + } + + u := c.baseURL.ResolveReference(rel) + + req, err := http.NewRequest(method, u.String(), body) + if err != nil { + return nil, err + } + + req.Header.Set("Content-Type", "application/json") + + // Set session cookie if there is one + if c.session != nil { + for _, cookie := range c.session.Cookies { + req.AddCookie(cookie) + } + } + + return req, nil +} + // NewRequest creates an API request. // A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. // Relative URLs should always be specified without a preceding slash. From 16619653d8c39c8433d525b3544eaf1f11107052 Mon Sep 17 00:00:00 2001 From: gm42 Date: Mon, 10 Oct 2016 12:54:45 +0200 Subject: [PATCH 2/2] Add test for NewRawRequest --- jira_test.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/jira_test.go b/jira_test.go index aefa3a8..fc856b4 100644 --- a/jira_test.go +++ b/jira_test.go @@ -145,6 +145,30 @@ func TestClient_NewRequest(t *testing.T) { } } +func TestClient_NewRawRequest(t *testing.T) { + c, err := NewClient(nil, testJIRAInstanceURL) + if err != nil { + t.Errorf("An error occured. Expected nil. Got %+v.", err) + } + + inURL, outURL := "rest/api/2/issue/", testJIRAInstanceURL+"rest/api/2/issue/" + + outBody := `{"key":"MESOS"}` + "\n" + inBody := outBody + req, _ := c.NewRawRequest("GET", inURL, strings.NewReader(outBody)) + + // Test that relative URL was expanded + if got, want := req.URL.String(), outURL; got != want { + t.Errorf("NewRawRequest(%q) URL is %v, want %v", inURL, got, want) + } + + // Test that body was JSON encoded + body, _ := ioutil.ReadAll(req.Body) + if got, want := string(body), outBody; got != want { + t.Errorf("NewRawRequest(%v) Body is %v, want %v", inBody, got, want) + } +} + func testURLParseError(t *testing.T, err error) { if err == nil { t.Errorf("Expected error to be returned")