1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 // Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests,
15 // wrapping a base RoundTripper and adding an Authorization header
16 // with a token from the supplied Sources.
18 // Transport is a low-level mechanism. Most code will use the
19 // higher-level Config.Client method instead.
20 type Transport struct {
21 // Source supplies the token to add to outgoing requests'
22 // Authorization headers.
25 // Base is the base RoundTripper used to make HTTP requests.
26 // If nil, http.DefaultTransport is used.
27 Base http.RoundTripper
29 mu sync.Mutex // guards modReq
30 modReq map[*http.Request]*http.Request // original -> modified
33 // RoundTrip authorizes and authenticates the request with an
34 // access token from Transport's Source.
35 func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
36 reqBodyClosed := false
46 return nil, errors.New("oauth2: Transport's Source is nil")
48 token, err := t.Source.Token()
53 req2 := cloneRequest(req) // per RoundTripper contract
54 token.SetAuthHeader(req2)
55 t.setModReq(req, req2)
56 res, err := t.base().RoundTrip(req2)
58 // req.Body is assumed to have been closed by the base RoundTripper.
65 res.Body = &onEOFReader{
67 fn: func() { t.setModReq(req, nil) },
72 // CancelRequest cancels an in-flight request by closing its connection.
73 func (t *Transport) CancelRequest(req *http.Request) {
74 type canceler interface {
75 CancelRequest(*http.Request)
77 if cr, ok := t.base().(canceler); ok {
79 modReq := t.modReq[req]
82 cr.CancelRequest(modReq)
86 func (t *Transport) base() http.RoundTripper {
90 return http.DefaultTransport
93 func (t *Transport) setModReq(orig, mod *http.Request) {
97 t.modReq = make(map[*http.Request]*http.Request)
100 delete(t.modReq, orig)
106 // cloneRequest returns a clone of the provided *http.Request.
107 // The clone is a shallow copy of the struct and its Header map.
108 func cloneRequest(r *http.Request) *http.Request {
109 // shallow copy of the struct
110 r2 := new(http.Request)
112 // deep copy of the Header
113 r2.Header = make(http.Header, len(r.Header))
114 for k, s := range r.Header {
115 r2.Header[k] = append([]string(nil), s...)
120 type onEOFReader struct {
125 func (r *onEOFReader) Read(p []byte) (n int, err error) {
126 n, err = r.rc.Read(p)
133 func (r *onEOFReader) Close() error {
139 func (r *onEOFReader) runFunc() {
140 if fn := r.fn; fn != nil {