github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/api/cloudcontroller/ccv2/request.go (about)

     1  package ccv2
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  	"net/url"
     8  
     9  	"code.cloudfoundry.org/cli/api/cloudcontroller"
    10  )
    11  
    12  // Params represents URI parameters for a request.
    13  type Params map[string]string
    14  
    15  // requestOptions contains all the options to create an HTTP request.
    16  type requestOptions struct {
    17  	// Body is the request body
    18  	Body io.ReadSeeker
    19  
    20  	// Method is the HTTP method of the request.
    21  	Method string
    22  
    23  	// Query is a list of HTTP query parameters
    24  	Query url.Values
    25  
    26  	// RequestName is the name of the request (see routes)
    27  	RequestName string
    28  
    29  	// URI is the URI of the request.
    30  	URI string
    31  
    32  	// URIParams are the list URI route parameters
    33  	URIParams Params
    34  }
    35  
    36  // newHTTPRequest returns a constructed HTTP.Request with some defaults.
    37  // Defaults are applied when Request fields are not filled in.
    38  func (client Client) newHTTPRequest(passedRequest requestOptions) (*cloudcontroller.Request, error) {
    39  	var request *http.Request
    40  	var err error
    41  	if passedRequest.URI != "" {
    42  		request, err = http.NewRequest(
    43  			passedRequest.Method,
    44  			fmt.Sprintf("%s%s", client.API(), passedRequest.URI),
    45  			passedRequest.Body,
    46  		)
    47  	} else {
    48  		request, err = client.router.CreateRequest(
    49  			passedRequest.RequestName,
    50  			map[string]string(passedRequest.URIParams),
    51  			passedRequest.Body,
    52  		)
    53  		if err == nil {
    54  			request.URL.RawQuery = passedRequest.Query.Encode()
    55  		}
    56  	}
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	request.Header = http.Header{}
    62  	request.Header.Set("Accept", "application/json")
    63  	request.Header.Set("User-Agent", client.userAgent)
    64  
    65  	if passedRequest.Body != nil {
    66  		request.Header.Set("Content-Type", "application/json")
    67  	}
    68  
    69  	// Make sure the body is the same as the one in the request
    70  	return cloudcontroller.NewRequest(request, passedRequest.Body), nil
    71  }