github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/provider/azure/internal/azuretesting/recorder.go (about) 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 }