Skip to content

Commit c1d0c79

Browse files
committed
Rewrite pagination links in BitBucket responses
1 parent f160a66 commit c1d0c79

File tree

1 file changed

+52
-4
lines changed

1 file changed

+52
-4
lines changed

api/bitbucket.go

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
package api
22

33
import (
4+
"bytes"
45
"context"
6+
"encoding/json"
57
"errors"
8+
"io/ioutil"
69
"net/http"
710
"net/http/httputil"
811
"net/url"
912
"regexp"
13+
"strings"
1014
"sync"
1115

1216
"golang.org/x/oauth2"
@@ -169,13 +173,57 @@ func (bb *BitBucketGateway) authenticate(w http.ResponseWriter, r *http.Request)
169173
return errors.New("Access to endpoint not allowed: your role doesn't allow access")
170174
}
171175

176+
func rewriteBitBucketLink(link, endpointAPIURL, proxyAPIURL string) string {
177+
return proxyAPIURL + strings.TrimPrefix(link, endpointAPIURL)
178+
}
179+
180+
func rewriteLinksInBitBucketResponse(resp *http.Response, endpointAPIURL, proxyAPIURL string) error {
181+
body, err := ioutil.ReadAll(resp.Body)
182+
if err != nil {
183+
return err
184+
}
185+
186+
var b map[string]interface{}
187+
if err := json.Unmarshal(body, &b); err != nil {
188+
return err
189+
}
190+
191+
if next, ok := b["next"].(string); ok {
192+
b["next"] = rewriteBitBucketLink(next, endpointAPIURL, proxyAPIURL)
193+
}
194+
195+
if prev, ok := b["previous"].(string); ok {
196+
b["previous"] = rewriteBitBucketLink(prev, endpointAPIURL, proxyAPIURL)
197+
}
198+
199+
newBody, err := json.Marshal(b)
200+
println(newBody)
201+
resp.Body = ioutil.NopCloser(bytes.NewReader(newBody))
202+
203+
return nil
204+
}
205+
172206
type BitBucketTransport struct{}
173207

174208
func (t *BitBucketTransport) RoundTrip(r *http.Request) (*http.Response, error) {
209+
ctx := r.Context()
210+
config := getConfig(ctx)
175211
resp, err := http.DefaultTransport.RoundTrip(r)
176-
if err == nil {
177-
// remove CORS headers from BitBucket and use our own
178-
resp.Header.Del("Access-Control-Allow-Origin")
212+
if err != nil {
213+
return resp, err
179214
}
180-
return resp, err
215+
216+
// remove CORS headers from BitBucket and use our own
217+
resp.Header.Del("Access-Control-Allow-Origin")
218+
219+
if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
220+
repo := config.BitBucket.Repo
221+
apiURL := singleJoiningSlash(config.BitBucket.Endpoint, "/repositories/"+repo)
222+
err = rewriteLinksInBitBucketResponse(resp, apiURL, "")
223+
if err != nil {
224+
return resp, err
225+
}
226+
}
227+
228+
return resp, nil
181229
}

0 commit comments

Comments
 (0)