github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/google.golang.org/cloud/internal/cloud.go (about)

     1  // Copyright 2014 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package internal provides support for the cloud packages.
    16  //
    17  // Users should not import this package directly.
    18  package internal
    19  
    20  import (
    21  	"fmt"
    22  	"net/http"
    23  )
    24  
    25  const userAgent = "gcloud-golang/0.1"
    26  
    27  // UATransport is an http.RoundTripper that appends
    28  // Google Cloud client's user-agent to the original
    29  // request's user-agent header.
    30  type UATransport struct {
    31  	// Base represents the actual http.RoundTripper
    32  	// the requests will be delegated to.
    33  	Base http.RoundTripper
    34  }
    35  
    36  // RoundTrip appends a user-agent to the existing user-agent
    37  // header and delegates the request to the base http.RoundTripper.
    38  func (t *UATransport) RoundTrip(req *http.Request) (*http.Response, error) {
    39  	req = cloneRequest(req)
    40  	ua := req.Header.Get("User-Agent")
    41  	if ua == "" {
    42  		ua = userAgent
    43  	} else {
    44  		ua = fmt.Sprintf("%s;%s", ua, userAgent)
    45  	}
    46  	req.Header.Set("User-Agent", ua)
    47  	return t.Base.RoundTrip(req)
    48  }
    49  
    50  // cloneRequest returns a clone of the provided *http.Request.
    51  // The clone is a shallow copy of the struct and its Header map.
    52  func cloneRequest(r *http.Request) *http.Request {
    53  	// shallow copy of the struct
    54  	r2 := new(http.Request)
    55  	*r2 = *r
    56  	// deep copy of the Header
    57  	r2.Header = make(http.Header)
    58  	for k, s := range r.Header {
    59  		r2.Header[k] = s
    60  	}
    61  	return r2
    62  }