Skip to content

Commit

Permalink
Add header field to transport
Browse files Browse the repository at this point in the history
Signed-off-by: Forest Eckhardt <[email protected]>
  • Loading branch information
Sophie Wigmore authored and ryanmoran committed Jun 25, 2020
1 parent 9a35314 commit 947aca1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
14 changes: 13 additions & 1 deletion cargo/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,19 @@ import (
"strings"
)

type Transport struct{}
type Transport struct{
header http.Header
}

func NewTransport() Transport {
return Transport{}
}

func (t Transport) WithHeader(header http.Header) Transport {
t.header = header
return t
}

func (t Transport) Drop(root, uri string) (io.ReadCloser, error) {
if strings.HasPrefix(uri, "file://") {
file, err := os.Open(filepath.Join(root, strings.TrimPrefix(uri, "file://")))
Expand All @@ -30,10 +37,15 @@ func (t Transport) Drop(root, uri string) (io.ReadCloser, error) {
return nil, fmt.Errorf("failed to parse request uri: %s", err)
}

if t.header != nil {
request.Header = t.header
}

response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, fmt.Errorf("failed to make request: %s", err)
}

return response.Body, nil
}

33 changes: 28 additions & 5 deletions cargo/transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,20 @@ func testTransport(t *testing.T, context spec.G, it spec.S) {

it.Before(func() {
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/some-bundle":
w.Write([]byte("some-bundle-contents"))
default:
http.NotFound(w, req)
if req.Header.Get("header") == "some-header" {
switch req.URL.Path {
case "/some-bundle-with-header":
w.Write([]byte("some-bundle-with-header-contents"))
default:
http.NotFound(w, req)
}
} else {
switch req.URL.Path {
case "/some-bundle":
w.Write([]byte("some-bundle-contents"))
default:
http.NotFound(w, req)
}
}
}))
})
Expand All @@ -54,6 +63,20 @@ func testTransport(t *testing.T, context spec.G, it spec.S) {
Expect(bundle.Close()).To(Succeed())
})

context("when there are request headers", func() {
it("downloads the file from a URI", func() {
bundle, err := transport.WithHeader(http.Header{"header": []string{"some-header"}}).
Drop("", fmt.Sprintf("%s/some-bundle-with-header", server.URL))
Expect(err).NotTo(HaveOccurred())

contents, err := ioutil.ReadAll(bundle)
Expect(err).NotTo(HaveOccurred())
Expect(string(contents)).To(Equal("some-bundle-with-header-contents"))

Expect(bundle.Close()).To(Succeed())
})
})

context("failure cases", func() {
context("when the uri is malformed", func() {
it("returns an error", func() {
Expand Down

0 comments on commit 947aca1

Please sign in to comment.