~juju-qa/ubuntu/xenial/juju/2.0-rc2

« back to all changes in this revision

Viewing changes to src/github.com/juju/juju/provider/azure/internal/azuretesting/recorder.go

  • Committer: Nicholas Skaggs
  • Date: 2016-09-30 14:39:30 UTC
  • mfrom: (1.8.1)
  • Revision ID: nicholas.skaggs@canonical.com-20160930143930-vwwhrefh6ftckccy
import upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2015 Canonical Ltd.
 
2
// Licensed under the AGPLv3, see LICENCE file for details.
 
3
 
 
4
package azuretesting
 
5
 
 
6
import (
 
7
        "bytes"
 
8
        "io/ioutil"
 
9
        "net/http"
 
10
        "sync"
 
11
 
 
12
        "github.com/Azure/go-autorest/autorest"
 
13
)
 
14
 
 
15
// RequestRecorder returns an autorest.PrepareDecorator that records requests
 
16
// to ghe given slice.
 
17
func RequestRecorder(requests *[]*http.Request) autorest.PrepareDecorator {
 
18
        if requests == nil {
 
19
                return nil
 
20
        }
 
21
        var mu sync.Mutex
 
22
        return func(p autorest.Preparer) autorest.Preparer {
 
23
                return autorest.PreparerFunc(func(req *http.Request) (*http.Request, error) {
 
24
                        // Save the request body, since it will be consumed.
 
25
                        reqCopy := *req
 
26
                        if req.Body != nil {
 
27
                                var buf bytes.Buffer
 
28
                                if _, err := buf.ReadFrom(req.Body); err != nil {
 
29
                                        return nil, err
 
30
                                }
 
31
                                if err := req.Body.Close(); err != nil {
 
32
                                        return nil, err
 
33
                                }
 
34
                                reqCopy.Body = ioutil.NopCloser(&buf)
 
35
                                req.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))
 
36
                        }
 
37
                        mu.Lock()
 
38
                        *requests = append(*requests, &reqCopy)
 
39
                        mu.Unlock()
 
40
                        return req, nil
 
41
                })
 
42
        }
 
43
}