@@ -18,12 +18,16 @@ package http_test
1818
1919import (
2020 "bytes"
21+ "errors"
22+ "fmt"
2123 "io/ioutil"
2224 "net/http"
2325 "sync"
2426 "testing"
2527
2628 "github.com/ethereum/go-ethereum/common"
29+ "github.com/ethereum/go-ethereum/swarm/api"
30+ swarm "github.com/ethereum/go-ethereum/swarm/api/client"
2731 "github.com/ethereum/go-ethereum/swarm/storage"
2832 "github.com/ethereum/go-ethereum/swarm/testutil"
2933)
@@ -128,3 +132,61 @@ func TestBzzrGetPath(t *testing.T) {
128132 }
129133
130134}
135+
136+ // TestBzzRootRedirect tests that getting the root path of a manifest without
137+ // a trailing slash gets redirected to include the trailing slash so that
138+ // relative URLs work as expected.
139+ func TestBzzRootRedirect (t * testing.T ) {
140+ srv := testutil .NewTestSwarmServer (t )
141+ defer srv .Close ()
142+
143+ // create a manifest with some data at the root path
144+ client := swarm .NewClient (srv .URL )
145+ data := []byte ("data" )
146+ file := & swarm.File {
147+ ReadCloser : ioutil .NopCloser (bytes .NewReader (data )),
148+ ManifestEntry : api.ManifestEntry {
149+ Path : "" ,
150+ ContentType : "text/plain" ,
151+ Size : int64 (len (data )),
152+ },
153+ }
154+ hash , err := client .Upload (file , "" )
155+ if err != nil {
156+ t .Fatal (err )
157+ }
158+
159+ // define a CheckRedirect hook which ensures there is only a single
160+ // redirect to the correct URL
161+ redirected := false
162+ httpClient := http.Client {
163+ CheckRedirect : func (req * http.Request , via []* http.Request ) error {
164+ if redirected {
165+ return errors .New ("too many redirects" )
166+ }
167+ redirected = true
168+ expectedPath := "/bzz:/" + hash + "/"
169+ if req .URL .Path != expectedPath {
170+ return fmt .Errorf ("expected redirect to %q, got %q" , expectedPath , req .URL .Path )
171+ }
172+ return nil
173+ },
174+ }
175+
176+ // perform the GET request and assert the response
177+ res , err := httpClient .Get (srv .URL + "/bzz:/" + hash )
178+ if err != nil {
179+ t .Fatal (err )
180+ }
181+ defer res .Body .Close ()
182+ if ! redirected {
183+ t .Fatal ("expected GET /bzz:/<hash> to redirect to /bzz:/<hash>/ but it didn't" )
184+ }
185+ gotData , err := ioutil .ReadAll (res .Body )
186+ if err != nil {
187+ t .Fatal (err )
188+ }
189+ if ! bytes .Equal (gotData , data ) {
190+ t .Fatalf ("expected response to equal %q, got %q" , data , gotData )
191+ }
192+ }
0 commit comments